Python asyncio Cheat Sheet/Create a background task

Schedule a coroutine to run concurrently.

Section: Tasks and Concurrency

Create a background task

python
python
import asyncio

async def worker():
    await asyncio.sleep(1)
    print("done")

async def main():
    task = asyncio.create_task(worker())
    await task

asyncio.run(main())
Explanation

A Task wraps and schedules a coroutine. Keep a reference to avoid losing track of exceptions or cancellation.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Tasks and Concurrency
Consume results as tasks finish
Process faster tasks first using `as_completed()`.
OpenIn sheetpythonsame section
Run tasks concurrently with gather
Wait for multiple coroutines and collect results.
OpenIn sheetpythonsame section
Collect exceptions with gather
Keep other tasks running even if one fails.
OpenIn sheetpythonsame section
Use TaskGroup for structured concurrency
Run related tasks under a context manager.
OpenIn sheetpythonsame section
Wait until the first task completes
Use `asyncio.wait()` to control waiting behavior.
OpenIn sheetpythonsame section
Cancel a task
Request cancellation and await the task to observe it.
OpenIn sheetpython1 tag match