asyncio.create_task
When talking about asyncio functions, sometimes I used the word "coroutine" and sometimes "task". It's time to tell you the difference:
coroutineis what async function returns. It can be scheduled, switched, closed, and so on. It's quite similar to generators. In fact,awaitkeyword is nothing more than an alias foryield from, andasyncis a decorator turning the function from a generator into a coroutine.asyncio.Futureis like "promise" in JS. It is an object that eventually will hold a coroutine result when it is available. It hasdonemethod to check if the result is available,resultto get the result, and so on.asyncio.Taskis like if coroutine and future had a baby. This is what asyncio mostly works with. It can be scheduled, switched, canceled, and holds its result when ready.
There is a cool function asyncio.create_task that can turn a coroutine into a proper task. What's cool about it is that this task immediately gets scheduled. So, if your code later encounters await, there is a chance your task will be executed at that point.
import asyncio
async def child():
print('started child')
await asyncio.sleep(1)
print('finished child')
async def main():
asyncio.create_task(child())
print('before sleep')
await asyncio.sleep(0)
print('after sleep')
asyncio.run(main())
Output:
before sleep
started child
after sleep
What happened:
- When
create_taskis called, it is scheduled but not yet executed. - When
mainhitsawait, the scheduler switches tochild. - When
childhitsawait, the scheduler switches to another task, which ismain - When
mainfinished,asyncio.runreturned without waiting forchildto finish. It's dead in space now.
But what if you want to make sure a scheduled task finishes before exiting? You can pass the task into good old asyncio.gather. And later we'll see some ways to wait for it with timeouts or when you don't care about the result.
task = create_task(...)
...
await asyncio.gather(task)