shutdown() from an AsyncClient's handler #1361
-
When receiving a specific message, I'd like to shutdown. from threading import Timer
class Conn:
def __init__(self):
self.sio.on('foo', handler=self.foo)
async def run(self):
await self.sio.connect(...)
def foo(self, data):
if data["blah"] == "test":
# if "blah" == "test" inside message "foo", then shutdown() in
# 20 seconds.
# This doesn't work because we need to `wait` for `shutdown()`
t = Timer(20.0, lambda: self.sio.shutdown())
t.start()
g = Conn()
loop.create_task(g.run())
loop.run_forever() What's the right way to deal with such patterns? |
Beta Was this translation helpful? Give feedback.
Answered by
miguelgrinberg
Jul 8, 2024
Replies: 1 comment 1 reply
-
You can't use await asyncio.sleep(20)
await self.sio.shutdown() Or if you don't want to wait in your handler: async def shutdown_in_20():
await asyncio.sleep(20)
await self.sio.shutdown()
self.sio.start_background_task(shutdown_in_20) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
drzraf
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can't use
Timer
in an async application, since it is thread based and blocking under async. Try using sleep instead:Or if you don't want to wait in your handler: