1

I have a background thread in a very primitive rest server that I planned to build. The only problem is this background thread seem to run twice, the minimum reproducible code is here:

import threading
import time
from flask import Flask

app = Flask(__name__, template_folder='templates')

def feedworker():
    print("STARTING FEEDWORKER")
    while True: # background thread. never stop updating
        time.sleep(75)

def runbackground():
    feeder_thread = threading.Thread(target=feedworker)
    feeder_thread.daemon = True
    feeder_thread.start()

if __name__ == "__main__":
    runbackground()
    app.run(debug=True)

runbackground should start the background feedworker which hangs.The big problem is, it seem to start that twice (terminal output):

STARTING FEEDWORKER
 * Serving Flask app "testthread" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
STARTING FEEDWORKER
 * Debugger is active!
 * Debugger PIN: 297-719-925

All the logs (there are more) indicate that the feedworker has been started twice. but if you comment out the last line (app.run(debug=True)) or just the debug=True, it will run only once.

Why does the debugger cause it to run twice?

Rocky Li
  • 5,641
  • 2
  • 17
  • 33
  • whats the code of your Feeder class. specifically constructor if there's any? – BetaDev Apr 22 '19 at 01:51
  • @webDev, hold on, I just eliminated Feeder class and it seems it's a problem with running flask with threading that causes it to run twice, I'll update the question – Rocky Li Apr 22 '19 at 01:52
  • yea because I tried same code eliminating flask and defining basic feeder class. Its calling only once. – BetaDev Apr 22 '19 at 01:53
  • 1
    Don't use threads in WSGI applications, since the threads are usually managed by the the WSGI server. In your case the reloader of the development server starts a new thread on every reload. – Klaus D. Apr 22 '19 at 01:56

0 Answers0