Skip to content

Instantly share code, notes, and snippets.

@amatai
Last active March 17, 2021 21:05
Show Gist options
  • Save amatai/ad05bd8d2ff74134e7b79c4cc0f7dc33 to your computer and use it in GitHub Desktop.
Save amatai/ad05bd8d2ff74134e7b79c4cc0f7dc33 to your computer and use it in GitHub Desktop.
Python asyncio: how to cleanly handle sighandlers and close all pending tasks
#!/usr/bin/env python3.6
import asyncio
import signal
async def taskX(task_name, loop):
while True:
try:
# simulate long running task
print("Task {} rnning...".format(task_name))
await asyncio.sleep(10, loop=loop)
except asyncio.CancelledError:
print("Task {} cancelled. Returning".format(task_name))
return
async def signal_handler(signame, loop):
# Call ny tasks that provide `stop` method
# await taskx.stop()
for task in asyncio.Task.all_tasks(loop=loop):
# cancel all tasks other than this signal_handler
if task is not asyncio.Task.current_task():
task.cancel()
await asyncio.sleep(5, loop=loop); # or however you think is reanable to wait.
loop.stop()
loop = asyncio.get_event_loop()
for i in range(7):
asyncio.ensure_future(taskX("task_" + str(i), loop))
# Add signal handlers
for signame in ['SIGTERM', 'SIGINT', 'SIGHUP']:
loop.add_signal_handler(getattr(signal, signame),
lambda: asyncio.ensure_future(signal_handler(signame, loop)))
try:
loop.run_forever()
finally:
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment