How to create an asyncio task

An asyncio task is a high-level construct in the asyncio library representing a coroutine executed by the event loop. In other words, it's a way to schedule a coroutine to run asynchronously.

Tasks are a convenient way to manage multiple coroutines running concurrently, allowing us to track their progress and easily handle errors. They're a powerful tool in the asyncio library that makes writing scalable, efficient, and asynchronous code in Python easy.

To create a task, we must first define a coroutine function using the async def syntax. For example:

async def coroutine():
# do some asynchronous work here

We can then create a task by passing the coroutine to the asyncio.create_task() function:

my_task = asyncio.create_task(my_coroutine())

The create_task() function schedules the coroutine to run and returns a task object that we can use to monitor its status, cancel it, or await its completion.

The create_task() function

The create_task() function is a built-in function provided by the asyncio library in Python to create a task from a coroutine. It schedules the coroutine to run asynchronously and returns a task object that can be used to track the status of the coroutine.

Example

The coding example of creating an asyncio task is as follows:

import asyncio
async def my_task(task_name, seconds):
"""
This is an example coroutine that takes a name and a number of seconds
as input, and waits for that many seconds before returning a message.
"""
print(f"{task_name} started")
await asyncio.sleep(seconds) # This simulates some work being done
print(f"{task_name} finished")
return f"{task_name} completed in {seconds} seconds"
async def main():
"""
This is the main coroutine that creates and runs several subtasks in parallel.
"""
# Create a list of tasks to run concurrently
tasks = [
asyncio.create_task(my_task("Task 1", 3)),
asyncio.create_task(my_task("Task 2", 2)),
asyncio.create_task(my_task("Task 3", 1)),
]
# Wait for all tasks to complete and retrieve their results
results = await asyncio.gather(*tasks)
print(results)
# Run the main coroutine in the asyncio event loop
asyncio.run(main())

Explanation

The explanation to the code is given below:

  • Line 1: The import asyncio statement is used to import the asyncio library.

  • Line 3: We define an async function my_task (a coroutine) which takes in the task_name and seconds as input and waits for that many seconds before returning a message.

  • Line 8: We print the input task name.

  • Line 9: The await asyncio.sleep(seconds) is used to pause the execution of a coroutine for a specified number of seconds. When a coroutine reaches an await asyncio.sleep(seconds), it will be suspended and added to the event loop's task queue to be resumed later.

  • Line 10: We print that the task has finished.

  • Line 11: We also print the time the task takes to run.

  • Line 13: The main() function is the main coroutine that creates and runs several subtasks in parallel.

  • Line 18–22: We then create a list of tasks to run concurrently using the asyncio.create_task() function, passing in the my_task() function along with some arguments, including the task's name and seconds.

  • Line 25: The asyncio.gather() function is then used to wait for all the tasks to complete and retrieve their results.

  • Line 26: We print the result to the console.

  • Line 29: Finally, the asyncio.run() function is called to run the main() coroutine in the asyncio event loop.

Conclusion

In conclusion, asyncio tasks are an essential component of the asyncio library, enabling developers to write concurrent and scalable code in Python. Using asyncio tasks can have several benefits, including improved performance, scalability, simplified code, and better resource management.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved