Solution
# ...
from threading import Event
thread_event = Event()
# ...
@socketio.on('collectLiveData')
def collectLiveData():
global thread
with thread_lock:
if thread is None:
thread_event.set()
thread = socketio.start_background_task(background_thread, thread_event)
def background_thread(event):
"""Example of how to send server generated events to clients."""
global thread
count = 0
try:
while event.is_set():
socketio.sleep(1)
count += 1
socketio.emit('my_response', {'count': count})
finally:
event.clear()
thread = None
@socketio.on("stopCollectingLiveData")
def stopCollectingLiveData():
global thread
thread_event.clear()
with thread_lock:
if thread is not None:
thread.join()
thread = None