asyncio - how to stop background task cleanly

Marko Rauhamaa marko at pacujo.net
Sat Feb 6 15:37:06 EST 2016


Marko Rauhamaa <marko at pacujo.net>:

>     async def background_task(cancel_event):
>          while True:
>              await asyncio.wait(
>                  perform_task, cancel_event.wait,
>                  return_when=asyncio.FIRST_COMPETED)
>              if cancel_event_is_set()
>                  break
>              await asyncio.wait(
>                  cancel_event.wait, timeout=10,
>                  return_when=asyncio.FIRST_COMPETED)
>              if cancel_event_is_set()
>                  break

[Typo: cancel_event_is_set() ==> cancel_event.is_set().]

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)


Marko


More information about the Python-list mailing list