asyncio create_task to run forever
I expected the numbers to keep printing even after
some_func
is completed.
The argument to run_until_complete
controls how long the event loop is run. And once the event loop stops running, all coroutines are effectively suspended, not just the one that you've been waiting for. But you do have different options:
loop.run_until_complete(some_func())
- what you already used; run the event loop until thesome_func
coroutine finishes. Executes other coroutines in parallel during that time as well, but also stops executing them as soon as the event loop finishes.loop.run_forever()
- run the event loop until some coroutine or callback invokesloop.stop()
. If none of them do that, then the event loop will not halt, even if all the coroutines come to an end. In your case you'd callloop.create_task(while_loop())
followed byloop.create_task(some_func())
and thenloop.run_forever()
.loop.run_until_complete(asyncio.gather(while_loop(), some_func()))
run the event loop until both the specified coroutines finish. This (wait for all the tasks) is apparently what you expectedloop.run_until_complete()
to do automatically even if you name only one, except it doesn't work like that, it stops as soon as the specified coroutine finishes.asyncio.gather
can be used to wait for multiple coroutines at once. For a more fine-tuned control of waiting, also seeasyncio.wait
.
Since one of your coroutines runs forever, the last two options will be equivalent and will result in the expected output.