2

I'm making a Flask server and would like to have a process running in the background which will periodically call a function and execute the code in there. To test if this is possible I made a simple function which just prints out the datetime() then waits 10 seconds before looping around again. To allow the server to still run as usual I have also tried to place this function within it's own thread to allow it to run desperately and not affect the server from dealing with incoming requests. My code is below:

def periodic_calls():
while True:
    print datetime.datetime.now()
    print 'Thread Count: ' + str(threading.active_count())
    time.sleep(10)


if __name__ == '__main__':
    timerThread = threading.Thread(target=periodic_calls)
    timerThread.start()
    app.debug=True
    app.run()

The majority of this code was pulled from Executing periodic actions in Python.

The problem is the code inside the function periodic_calls()appears to be called twice every 10 seconds instead of just once. Output from the code above:

2015-08-06 14:27:51.825000
Thread Count: 2
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
2015-08-06 14:27:52.265000
Thread Count: 2
2015-08-06 14:28:01.828000
Thread Count: 2
2015-08-06 14:28:02.268000
Thread Count: 3
2015-08-06 14:28:11.829000
Thread Count: 2
2015-08-06 14:28:12.268000
Thread Count: 3
2015-08-06 14:28:21.830000
Thread Count: 2
2015-08-06 14:28:22.269000
Thread Count: 3

What is causing the third thread to be started and the function to be called twice instead of once? And how do I correct this?

Community
  • 1
  • 1
QweryBot
  • 457
  • 1
  • 4
  • 15

0 Answers0