asyncio - how to stop background task cleanly
Frank Millman
frank at chagford.com
Sun Feb 7 00:27:19 EST 2016
"Marko Rauhamaa" wrote in message news:8737t5shhp.fsf at elektro.pacujo.net...
> >
> Actually, cancellation is specially supported in asyncio (<URL:
> https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel>)
> so this should do:
>
> async def background_task():
> while True:
> await perform_task()
> await asyncio.sleep(10)
>
That's exactly what I needed - thanks, Marko
async def background_task()
try:
while True:
await perform_task()
await asyncio.sleep(10)
except asyncio.CancelledError:
await perform_cleanup()
At startup -
task = asyncio.ensure_future(background_task())
At shutdown -
task.cancel()
await asyncio.wait([task])
Works perfectly - thanks again.
Frank
More information about the Python-list
mailing list