asyncio.create_task schedules a coroutine to run concurrently and immediately returns an asyncio.Task representing that work. Unlike awaiting the coroutine directly, creating the task lets the current coroutine continue until it reaches an await. section 2.3.1
Use tasks effectively by following these rules:
- Create several tasks before awaiting them when operations should overlap; awaiting immediately inside a loop makes them run sequentially. section 2.3.2 section 4.3
- Await each task eventually so the event loop can finish its work and task results or exceptions can be handled. section 2.3.1
Run three delays concurrently
Create three tasks first, then await them. Three three-second delays complete in about three seconds rather than about nine seconds when they run sequentially. section 2.3.2
Listing 2.8 Creating a task
import asyncio
from util import delay
async def main():
sleep_for_three = asyncio.create_task(delay(3))
print(type(sleep_for_three))
result = await sleep_for_three
print(result)
asyncio.run(main())
Inspect a minimal runnable example showing task creation, task typing, and awaiting the result. section 2.3.1

