Issue
I have a background process started, but I have no idea how to stop the process. I've read through the documentation but there doesn't seem to be any built in function to kill the task. How should I resolve this? I am specifically referring to the stopCollectingLiveData() section.
@socketio.on('collectLiveData')
def collectLiveData():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(background_thread)
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(1)
count += 1
socketio.emit('my_response', {'count': count})
@socketio.on("stopCollectingLiveData")
def stopCollectingLiveData():
print('')
socketio.sleep()
Solution
You can stop the background thread with an event object, which you can pass as a parameter. As long as the event is set, the thread runs. When the event is cleared, the thread's execution is suspended.
# ...
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
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.