Python asyncio.create_task() function (with examples)

Updated: August 7, 2023 By: Khue Post a comment

This concise, example-oriented article is about the asyncio.create_task() function in Python.

Overview

asyncio.create_task() is a high-level function that was added to Python in version 3.7. The function is used for running coroutines concurrently as asyncio Tasks. A Task is a subclass of Future that wraps a coroutine and executes it on the event loop. Tasks allow you to manage the execution of multiple coroutines and get their results.

Syntax:

asyncio.create_task(coro, *, name=None)

Where:

  • coro: a coroutine object that will be wrapped into a Task.
  • name: an optional string that represents the name of the Task. If not provided, a default name is generated based on the function and its arguments.

The returned value of the function is a Task object that can be awaited or cancelled.

asyncio.create_task() is useful when you want to run multiple coroutines concurrently and get their results. For example, you can use it to perform parallel network requests, process data in parallel, or implement asynchronous timers.

Examples

Let’s examine a couple of practical examples to get a better understanding about asyncio.create_task(). These examples are arranged in order from basic to advanced.

Run two coroutines concurrently and get their results

This example shows how to use asyncio.create_task() to run two coroutines concurrently and get their results. The coroutines simulate some long-running operations using asyncio.sleep(). The program prints the current time, creates two tasks from the coroutines, waits for them to finish, and prints their results and the elapsed time:

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio
import time


# Define a coroutine that simulates a long-running operation
async def long_operation(message, delay):
    print(message)
    await asyncio.sleep(delay)  # Pause for delay seconds
    return f"Done after {delay} seconds"


# Define an async main function that creates and awaits two tasks
async def main():
    # Get the current time
    start = time.perf_counter()

    # Create two tasks from the coroutines
    task1 = asyncio.create_task(long_operation("Task 1 started", 3))
    task2 = asyncio.create_task(long_operation("Task 2 started", 2))

    # Wait for the tasks to finish and get their results
    result1 = await task1
    result2 = await task2

    # Print the results and the elapsed time
    print(result1)
    print(result2)
    end = time.perf_counter()
    print(f"Finished in {end - start:.2f} seconds")


# Run the main function using asyncio.run()
asyncio.run(main())

Output:

Task 1 started
Task 2 started
Done after 3 seconds
Done after 2 seconds
Finished in 3.00 seconds

Note that the program finishes in 3 seconds, which is the maximum delay of the two tasks, instead of 5 seconds, which is the sum of their delays. This clearly proves an important point: the tasks were running concurrently, not sequently.

Create an asynchronous timer

In this example, we’ll use asyncio.create_task() to implement an asynchronous timer that prints a message every second for a given duration. The code defines a coroutine that creates a task for the timer and awaits it. It also defines another coroutine that simulates some other work. The program runs both coroutines concurrently and prints their outputs.

# SlingAcademy.com
# This code uses Python 3.11.4

import asyncio


# Define a coroutine that implements an asynchronous timer
async def timer(duration):
    # Loop for duration seconds
    for i in range(duration):
        # Print a message every second
        print(f"Timer: {i+1} second(s) passed")
        # Pause for one second
        await asyncio.sleep(1)
    # Return a message when the timer is done
    return "Timer: done"


# Define a coroutine that simulates some other work
async def work():
    # Print a message
    print("Work: started")
    # Pause for two seconds
    await asyncio.sleep(2)
    # Return a message when the work is done
    return "Work: done"


# Define an async main function that creates and awaits two tasks
async def main():
    # Create a task for the timer with a duration of 5 seconds
    timer_task = asyncio.create_task(timer(5))
    # Create a task for the work
    work_task = asyncio.create_task(work())

    # Wait for both tasks to finish and get their results
    timer_result = await timer_task
    work_result = await work_task

    # Print the results
    print(timer_result)
    print(work_result)


# Run the main function using asyncio.run()
asyncio.run(main())

Output:

Timer: 1 second(s) passed
Work: started
Timer: 2 second(s) passed
Timer: 3 second(s) passed
Timer: 4 second(s) passed
Timer: 5 second(s) passed
Timer: done
Work: done