asyncio - how to stop background task cleanly

Frank Millman frank at chagford.com
Sat Feb 6 09:01:49 EST 2016


"Marko Rauhamaa"  wrote in message news:87lh6ys052.fsf at elektro.pacujo.net...
>
> "Frank Millman" <frank at chagford.com>:
>
> > 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.
>
> Here (and really, only here) is where asyncio shows its superiority over
> threads: you can multiplex.
>
> You should
>
>    await asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED)
>
> to deal with multiple alternative stimuli.
>

Thanks, Marko, that works very well.

It took me a while to get it working, because I initiate shutting down the 
program from another thread. Eventually I figured out that I could put all 
my event loop shutdown procedures into a coroutine, and then call 
asyncio.run_coroutine_threadsafe() from the main thread.

Now I just have one problem left. I will keep experimenting, but if someone 
gives me a hint in the meantime it will be appreciated.

I run my background task like this -

    stop_task = False

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

I stop the task by setting stop_task to True. It works, but it waits for the 
10-second sleep to expire before it is actioned.

With threading, I could set up a threading.Event(), call 
evt.wait(timeout=10) to run the loop, and evt.set() to stop it. It stopped 
instantly.

Is there an equivalent in asyncio?

Thanks

Frank




More information about the Python-list mailing list