["python","rest","flask"]
How can I add a background thread to flask?

I'm busy writing a small game server to try out flask. The game exposes an API via REST to users. It's easy for users to perform actions and query data, however I'd like to service the "game world" outside the app.run() loop to update game entities, etc. Given that Flask is so cleanly implemented, I'd like to see if there's a Flask way to do this.
Your additional threads must be initiated from the same app that is called by the WSGI server. The example below creates a background timer-thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions. import threading import atexit from flask import Flask POOL_TIME = 5 #Seconds # variables that are accessible from anywhere common_data_struct = {} # lock to control access to variable data_lock = threading.Lock() # timer handler your_timer = threading.Timer(0,lambda x: None,()) def create_app(): app = Flask(__name__) def interrupt(): global your_timer your_timer.cancel() def do_stuff(): global common_data_struct global your_timer with data_lock: pass # Do your stuff with common_data_struct Here # Set the next timeout to happen your_timer = threading.Timer(POOL_TIME, do_stuff, ()) your_timer.start() def do_stuff_start(): # Do initialisation stuff here global your_timer # Create your timer your_timer = threading.Timer(POOL_TIME, do_stuff, ()) your_timer.start() # Initiate do_stuff_start() # When you kill Flask (SIGTERM), cancels the timer atexit.register(interrupt) return app app = create_app() Call it from Gunicorn with something like this: gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app Signal termination works best on OS's other than Windows. Although this creates a new timer after each timeout, the other timers should eventually be garbage-collected.