Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python relations between run_until_complete and ensure_future

This is a follow up question to this question:

Why do most asyncio examples use loop.run_until_complete()?

I'm trying to figure out how asynchronous programming work in python. There's something very basic which I'm still not sure about..

when having this line code: asyncio.ensure_future(someTask) , will this line ALONE actually enqueue the Future returned in the default event loop and start the task? Or do I ALSO need to call loop.run_until_complete(someTask) (or some other kind of run) before that in order to get the event loop up and running?

like image 364
Yonatan Nir Avatar asked Dec 17 '25 14:12

Yonatan Nir


1 Answers

asyncio.ensure_future(someTask) will this line ALONE actually enqueue the Future returned in the default event loop and start the task?

It will schedule the coroutine, but it won’t run it. You still need to run the loop to do that. You can do that with

loop.run_forever()

If you want the loop to run until someTask is done rather than forever, use

future = asyncio.ensure_future(someTask)
loop.run_until_complete(future)

Don’t call both asyncio.ensure_future(someTask) and loop.run_until_complete(someTask) or you’ll end up with a RuntimeError since someTask will have already been scheduled.

like image 108
dirn Avatar answered Dec 20 '25 18:12

dirn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!