stopping worker #3750
-
In the documentation, it says that to cancel a worker we can use and use But what I'm facing is that I have a worker running in the background but the program says No Active Worker. # some other imports
from textual.widgets import ListView, ListItem
from textual.widget import Widget
from textual import work
import socketio
websocket = socketio.SimpleClient()
websocket.connect("http://localhost:3000")
class MessageAreaWidget(Widget):
list_view = reactive(ListView(*[], id="messages-list-view"), always_update=True)
default_messages = ["Welcome Back", "How are you"]
def compose(self) -> ComposeResult:
yield Container(self.list_view, id="messages-container")
for message in self.default_messages:
self.list_view.append(
ListItem(Static(message), class="list-item")
)
class MyScreen(Screen):
def compose(self) -> ComposeResult:
yield MessageAreaWidget()
@work(exclusive=True, thread=True)
def websocket_receive(self):
while True:
event = websocket.receive()
# event[0] is event name
# event[1] is message
if event[0] == "newmessage":
self.query_one(MessageAreaWidget).list_view.append(
ListItem(Static(event[1]), classes="list-item")
)
def on_screen_resume(self, event: events.ScreenSuspend) -> None:
self.websocket_receive()
def on_screen_suspend(self, event: events.ScreenSuspend) -> None:
# cancel worker
try:
current_worker = get_current_worker()
if current_worker.is_running: current_worker.cancel()
except NoActiveWorker:
log("not active worker") I always get no active worker. Why is that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You may want to have a read again of the parts of the guide to workers that deal with thread workers, it gives an example of calling To cancel a specific worker from outside of it, my approach would be to give the worker a unique group name and then, when you want to cancel, use @work(exclusive=True, thread=True, group="websocket")
def websocket_receive(self):
...
# Later on in the code...
self.workers.cancel_group(self, "websocket") |
Beta Was this translation helpful? Give feedback.
get_current_worker
is a function for doing just that, getting the current worker; that is: getting the worker you're inside of. You can have multiple workers all running at the same time so from outside of any given worker there is no current worker.You may want to have a read again of the parts of the guide to workers that deal with thread workers, it gives an example of calling
get_current_worker
, and also highlights the issue of thread safety; in your code above you're attempting to update widgets in a non-thread-safe way (not the issue here, but an issue you'll run into).To cancel a specific worker from outside of it, my approach would be to give the worker a unique group name and t…