7.1 Task Creation
The Task class in the asyncio module is used to manage coroutine execution. Tasks are wrappers for coroutines that let you manage their execution and track their state. The Task class allows coroutines to run concurrently, managed through the event loop.
Main methods of the Task class
The Task class is a kind of wrapper around a coroutine that provides additional capabilities like:
Managing coroutine execution:
Tasks make it easy to control coroutine execution, monitor their state, and get results.
Task cancellation:
The ability to cancel tasks makes the Task class useful for managing long operations that may need to be stopped before completion.
Callbacks:
Tasks support adding callbacks, allowing additional actions to be performed when tasks complete.
Task creation:
Tasks are created using the function asyncio.create_task(coroutine) or the method loop.create_task(coroutine), which schedules coroutine execution.
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
async def main():
task = asyncio.create_task(say_hello())
await task
asyncio.run(main())
7.2 Main Methods
Method Task.cancel():
Requests task cancellation. If the task is not done yet, it will be completed with a CancelledError exception.
Let's write a small program to demonstrate this.
Create an asynchronous task that simply waits for 10 secondsWrap it in aTaskobjectWait a second for the task to startCancel the task –task.cancel()-
If we try to wait for the task to complete usingawait, we will get aCancelledErrorexception.
import asyncio
async def main():
task = asyncio.create_task(asyncio.sleep(10))
await asyncio.sleep(1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task was cancelled")
asyncio.run(main())
Method Task.result():
Returns the result of the task execution. If the task finished with an exception, it will be raised when calling result().
import asyncio
async def main():
task = asyncio.create_task(asyncio.sleep(1, result='Completed'))
result = await task
print(result) # Output: Completed
asyncio.run(main())
In our case, we didn't even need to write additional code — the await operator knows how to deal with a Task object: after the task completes, it will automatically call its result() method and return the obtained result.
Method Task.exception():
Returns the exception raised by the task. If the task completed without an exception, it returns None.
import asyncio
async def main():
task = asyncio.create_task(asyncio.sleep(1))
try:
result = await task
except Exception as e:
print(f"Task failed with exception: {e}")
asyncio.run(main())
No additional code is needed either — if an exception occurs in the task, the exception() method will be called by the await operator.
Method Task.add_done_callback(callback):
Adds a callback function, which will be called upon task completion.
import asyncio
def callback(future):
print("Task completed")
async def main():
task = asyncio.create_task(asyncio.sleep(1))
task.add_done_callback(callback)
await task
asyncio.run(main())
You can add a function to a task that will be automatically called when the task completes. This approach makes the code very flexible. Moreover, you can add multiple functions, and they can be added to any tasks.
Method Task.done():
Returns True if the task is done (successfully, with error, or was canceled).
import asyncio
async def main():
task = asyncio.create_task(asyncio.sleep(1))
await asyncio.sleep(1.5)
print(task.done()) # Output: True
asyncio.run(main())
The done() method can tell you whether the task finished successfully. Or rather, if it completed or was canceled, because if an exception occurred, technically the task may not be complete, but it wasn't canceled either. In general, if the task was canceled (cancel), the method will return False, otherwise, it returns True.
GO TO FULL VERSION