asyncio - how to stop background task cleanly

Frank Millman frank at
Sat Feb 6 02:55:26 EST 2016

Hi all

It is easy enough to set up a task to run in the background every 10 seconds 
using asyncio -

    async def background_task():
        while True:
            await perform_task()
            await asyncio.sleep(10)


When shutting the main program down, I want to stop the task, but I cannot 
figure out how to stop it cleanly - i.e. wait until it has finished the 
current task and possibly performed some cleanup, before continuing.

    async def background_task():
        await perform_setup()
        while condition:
            await perform_task()
            await asyncio.sleep(10)
        await perform_cleanup()

Previously I would run the task in another thread, then set a flag to tell 
it to stop, then join() the thread which would block until the task had 
finished. I used threading.Event as the flag, which allows it to 'sleep' 
using wait() with a timeout value, but reacts instantly when set() is 
called, so it was ideal.

Is there a way to achieve this using asyncio?


Frank Millman

More information about the Python-list mailing list