liveBook · Manning

Asyncio.create_task

As explained in Python Concurrency with asyncio

asyncio.create_task is an asyncio function that schedules a coroutine for concurrent execution and returns a task representing it.

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

How Python Concurrency with asyncio covers it

How deep it goes
Defines task creation and scheduling, then demonstrates multiple tasks; defers detailed exception handling.
Examples
Uses delay coroutines, three-task timing comparisons, status messages, and list-comprehension patterns.
What it assumes
Assumes async coroutine syntax and await expressions, while distinguishing tasks from coroutines through runnable examples.
What you can do after
Apply it via asyncio.create_task to launch concurrent coroutines and await their completion.
How it connects
Links coroutines, await expressions, the event loop, and concurrency.

Also explained in

Compare how 2 books explain asyncio.create_task →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.