Course contentsShow
← Python
Lesson 888 of 1,06014. Concurrency and PerformanceFree lesson

Scheduling Concurrent Tasks with Task Objects

Wrap coroutines into tasks to enable simultaneous execution and track their progress within the event loop.

Scheduling Concurrent Tasks with Task Objects

In this lesson, you will learn how to wrap coroutines into Task objects to transition from sequential asynchronous execution to true concurrent task management.

Up to this point, you have defined coroutines using async and executed them using await. However, when you await a coroutine directly, the event loop pauses execution at that line until the coroutine completes. If you want to trigger multiple operations so they run "at the same time," you need a way to hand them off to the event loop's scheduler without stopping the flow of your program.

This is where Task objects come in. When you wrap a coroutine in a Task (typically using asyncio.create_task()), the event loop schedules the coroutine to run as soon as possible. Critically, the create_task() function returns immediately, allowing your code to continue to the next line while the task progresses in the background.

Consider this scenario where we perform two I/O-bound operations:

import asyncio

async def fetch_data(id, delay):
    print(f"Task {id} starting...")
    await asyncio.sleep(delay)
    print(f"Task {id} finished.")
    return f"Data {id}"

async def main():
    # Scheduling tasks allows them to run concurrently
    task1 = asyncio.create_task(fetch_data(1, 2))
    task2 = asyncio.create_task(fetch_data(2, 1))

    # We can now do other work here while they run
    print("Tasks are running in the background.")

    # Await the tasks to retrieve their results
    result1 = await task1
    result2 = await task2
    print(f"Results: {result1}, {result2}")

asyncio.run(main())

In this example, both fetch_data coroutines are scheduled simultaneously. The event loop manages the switching between these tasks whenever one hits an await point (like asyncio.sleep). By keeping a reference to the Task object, you maintain the ability to track its progress, check for completion, or retrieve the return value later. If you simply called the coroutines without wrapping them in tasks, the second task would not start until the first one had finished entirely.

Key Takeaway: Wrapping a coroutine in a Task object allows the event loop to manage its execution concurrently, decoupling the scheduling of the operation from the requirement to wait for its immediate completion.