Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 40 ยท Tasks and Gathering

Creating Tasks with asyncio.create_task

Learn asyncio.create_task to run coroutines concurrently, how tasks differ from plain await, task names, results, cancellation, and why you must keep a reference.

So far every await waited for one thing to finish before the next line ran. To get real concurrency you need to start a coroutine without waiting for it. That is the job of a Task: asyncio.create_task(coro) schedules the coroutine on the event loop right away and returns a Task object. Your code continues immediately, and the task runs whenever the loop has a turn.

Await versus create_task

Compare running two jobs one after the other with running them as tasks:

Python Sequential await vs tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first block takes about 0.4 seconds; the second takes about 0.2, because both tasks were already running when we started waiting. Remember the rule: a coroutine runs only when awaited or wrapped in a task; a task starts running as soon as the loop gets control.

await a coroutine

Starts it now And waits right here
Next line blocked Until the result is ready

Sequential

1 / 2

When does a task start?

create_task only schedules; the task begins when the current coroutine next yields to the loop (at its next await). This explains the print order here:

Python Tasks start at the next await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading task results

A Task is a Future, so you collect its result by awaiting it, or by calling task.result() after it is done. Useful members:

Member Meaning
await task wait, then get the result (or raise its exception)
task.done() finished, failed or cancelled?
task.result() the return value (raises if failed or still pending)
task.exception() the exception, or None
task.cancel() request cancellation
task.cancelled() was it cancelled?
task.get_name() / set_name() a label for debugging

Give tasks a name with the name= argument. It appears in logs and tracebacks, which helps a lot when many tasks run:

Python Names and state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Keep a reference to every task

The event loop keeps only a weak reference to a task. If you create a task and never store it anywhere, Python's garbage collector may delete it in the middle of running. The official documentation says to save a reference until the task is done. For fire-and-forget work, the pattern is a set that discards finished tasks:

Python
background_tasks: set[asyncio.Task] = set()


def spawn(coro) -> asyncio.Task:
    task = asyncio.create_task(coro)
    background_tasks.add(task)                        # strong reference
    task.add_done_callback(background_tasks.discard)  # remove when finished
    return task

A TaskGroup does this bookkeeping for you and is preferable whenever the tasks belong to one piece of work.

Cancelling a task

task.cancel() schedules a CancelledError to be raised inside the task at its current await. The task can clean up in a finally block. Awaiting a cancelled task raises CancelledError in the waiter:

Python Cancelling a task

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always re-raise CancelledError after cleanup, or the cancellation is swallowed and the task keeps running. Cancellation has a full chapter later in the course; this is the basic shape.

Tasks that run forever

A task can loop forever as a background service, such as a heartbeat or a cache refresher. The owner is responsible for cancelling it:

Python A background heartbeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The gather(..., return_exceptions=True) after cancel() waits for the task to actually finish and absorbs its CancelledError. That "cancel, then wait" idiom keeps shutdown tidy.

Common mistakes

  • Not awaiting the task. If main() returns before the task finishes, the task is cancelled by asyncio.run, and its work is lost.
  • Losing the reference (see above).
  • Creating a task in a loop and awaiting each immediately: for x in items: await asyncio.create_task(f(x)) is just sequential. Create all tasks first, then await them (or use gather).
  • Calling create_task outside a running loop raises RuntimeError: no running event loop.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does asyncio.create_task(coro) return?

    It schedules the coroutine and gives you a Task you can await, cancel or inspect later.
  2. 2. When does a newly created task begin to run?

    create_task only schedules it. It starts at the next await (or sleep(0)) of the current coroutine.
  3. 3. Why should you keep a reference to a task you create?

    The documentation warns that an unreferenced task can be collected mid-run.
  4. 4. What should a task do after catching CancelledError for cleanup?

    Swallowing CancelledError breaks cancellation. Clean up, then raise again.

Summary

  • create_task schedules a coroutine to run concurrently and returns a Task immediately.
  • Tasks start at the creator's next await; await them to get results or exceptions.
  • Name tasks, inspect them with done(), result(), cancelled(), and keep references.
  • cancel() raises CancelledError inside the task; clean up and re-raise.

Next: gather and return values