Cancel asyncio task with the name

Viewed 730

I have n number of asyncio tasks running as below.

    import asyncio
    def main(tasks):
       for task in tasks:
          await asyncio.create_task(do_something(task),name=task['name'])
    asyncio.run(main(tasks))

After sometime I need to cancel only the particular task using task name.

1 Answers

You could find the task by name using asyncio.all_tasks():

task, = [task for task in asyncio.all_tasks() if task.get_name() == name]
task.cancel()

Note that get_name() requires Python 3.8. For earlier Python versions you can maintain your own name-to-task dictionary when you create the tasks.

Related