I'm trying to use background tasks with flask-socketio and run into two problems:
- when in reloader mode, the background task is started twice
- when changing the code, flask reloads but the background tasks are not killed
My code:
from flask import Flask
from flask_socketio import SocketIO
import random
application = Flask(__name__)
socketio = SocketIO(application, async_mode='eventlet')
import eventlet
eventlet.monkey_patch()
def background_thread():
print('starting backgound task')
thread_id = random.randint(1,100)
while True:
print(f'background thread {thread_id}')
socketio.sleep(1)
if __name__ == '__main__':
print('--------------------')
socketio.start_background_task(background_thread)
socketio.run(application, debug=True, use_reloader=True)
Output:
python application.py
--------------------
starting backgound task
background thread 26
* Restarting with stat
--------------------
starting backgound task
background thread 59
background thread 26
* Detected change in '/Users/philipp/code/nifmap/application.py', reloading
background thread 26
background thread 59
background thread 26
background thread 59
When I then hit ^C
then one background task is killed, but not the other. This happens only when I do debug=True
. How can I start the background task so that it's only started once and then it's killed upon reload?
The same happens when using gevent, starting with async_mode='eventlet'
and doing:
from gevent import monkey
monkey.patch_all()
Versions:
eventlet==0.33.0
Flask==2.0.2
Flask-SocketIO==5.1.1
Flask-WTF==0.15.1
greenlet==1.1.2
python-engineio==4.3.0
python-socketio==5.5.0
websocket-client==1.2.3
Werkzeug==2.0.2
Python 3.8.2