Tasks

Tasks#

Tasks are wrappers for co-routines. They add some management interface for the wrapped co-routine:

  • for querying state of execution: task.done()

  • retrieving results: task.result()

  • cancelling execution: task.cancel()

Creating a task directly triggers execution.

task = asyncio.create_task(friendly_wait_for(1))

print(f"{task=}")
print(f"Task completed: {task.done()}")
await task
print(f"Tasks result: {task.result()}")
task=<Task pending name='Task-6' coro=<friendly_wait_for() running at /var/folders/4f/zxcbb2rd6q98m0h5fzm9xljm0000gn/T/ipykernel_38563/14944068.py:1>>
Task completed: False
Done waiting for 1 seconds.
Tasks result: 1
task = asyncio.create_task(friendly_wait_for(5))

print(f"{task=}")
task=<Task pending name='Task-7' coro=<friendly_wait_for() running at /var/folders/4f/zxcbb2rd6q98m0h5fzm9xljm0000gn/T/ipykernel_38563/14944068.py:1>>

Task execution can be cancelled. In that case no result is set. Querying for the result will lead to an exception.

_ = task.cancel()

Querying task status of course works as expected.

print(f"Task cancelled: {task.cancelled()}")
print(f"Task completed: {task.done()}")
Task cancelled: False
Task completed: False