add_done_callback() method of asyncio.Task class in Python

The add_done_callback() registers a function with an asyncio.Task object, as a callback. The Python example prints the task name, task status and the task result from the context received inside the callback.

Task Updated 17 May 2022 1 min read

Overview

  • The add_done_callback() method adds a callback function to an asyncio.Task object which is called when the Task is done.
  • The task object itself is sent back to the call back through the context parameter.

Example

python
# Example Python program that adds a completion

            # call back to an asyncio.Task object

            import asyncio

            from datetime import datetime

# Callback - context object is the actual

            # task object

            def task_cb(context):

                print("Task completion received...")

                print("Name of the task:%s"%context.get_name())

                print("Wrapped coroutine object:%s"%context.get_coro())

                print("Task is done:%s"%context.done())

                print("Task has been cancelled:%s"%context.cancelled())

                print("Task result:%s"%context.result())

                print(type(context))

                print(context)

# A simple Python coroutine

            async def simple_coroutine():

                await asyncio.sleep(1)

                return 1

# Create an asyncio.Task object

            async def main():

                t1 = asyncio.create_task(simple_coroutine())

                t1.add_done_callback(task_cb)

                await t1

                print("Coroutine main() exiting")

# Execute the task

            el = asyncio.new_event_loop()

            asyncio.set_event_loop(el)

            asyncio.run(main())

Output

Output
Task completion received...

Name of the task:Task-2

Wrapped coroutine object:<coroutine object simple_coroutine at 0x106981540>

Task is done:True

Task has been cancelled:False

Task result:1

<class '_asyncio.Task'>

<Task finished name='Task-2' coro=<simple_coroutine() done, defined at /ex/example.py:19> result=1>

Coroutine main() exiting