'Catching Exceptions in Individual Tasks and Restarting Them
If I create a series of asyncio tasks in a top level class, all of which should essentially run forever, like so:
asyncio.create_task(...)
asyncio.create_task(...)
asyncio.create_task(...)
...
self.event_loop.run_forever()
# Once we fall out of the event loop, collect all remaining tasks,
# cancel them, and terminate the asyncio event loop
tasks = asyncio.Task.all_tasks()
group = asyncio.gather(*tasks, return_exceptions=True)
group.cancel()
self.event_loop.run_until_complete(group)
self.event_loop.close()
The above code doesn't handle the following situation, which I'm finding I need more and more, and I haven't seen an example in Googling or in the asyncio docs:
If one of the tasks fails with an exception, the exception doesn't get handled - all of the other tasks proceed, but that one task simply halts silently (other than the exception output).
So, how can I:
- Set up for the exception to be handled, so that the failure isn't silent any more
- Most importantly, restart the failed task, effectively running
asyncio.create_task(...)again, just for that task? This would seem to require finding the task that received the exception in the event loop, removing it, and adding a new one - how to do that is not clear to me. - Allow the tasks that didn't have issues to continue uninterrupted. Want to avoid any side effects of handling the task that received the exception.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
