Graceful shutdown from a different coroutine

31 views
Skip to first unread message

Vincent Le Goff

unread,
Mar 11, 2020, 11:40:05 AM3/11/20
to aio-...@googlegroups.com
Hi everyone,

Following the documentation, I've added coroutines that should start
with the server and keep on running as long as the server runs. They
watch it, if you like.  But they should also be able, under some
circumstances, to signal the server it should stop.  I'm looking for an
elegant way to do it.

app = web.Application()
app.add_routes([web.get('/', ...)])
app.on_startup.append(watcher)
web.run_app(app)

... with the coroutine 'watcher' looking something like:

async def watcher(app):
    asyncio.create_task(watch_server())

`watch_server` in my case is a coroutine.  It will run asynchronously
with the web server.  At some point it will have to stop the web server
itself.  And that's where I'm struggling.

Raising an exception from inside `watch_server` won't do the trick, of
course, since exceptions are intercepted on the task level, not the loop
level.  As far as I see, there's no server/application method to
gracefully terminate the web server while it's running.  I don't think I
have access to the task itself, or I could try to cancel it.  And
closing the loop isn't a good idea since the 'watch_server' coroutine is
running in the loop itself.

Am I missing something obvious here?

Thanks for your help,

Vincent
Reply all
Reply to author
Forward
0 new messages