Last active
November 2, 2022 01:52
-
-
Save kgriffs/d827db257815701a30c1a03a66e6d09f to your computer and use it in GitHub Desktop.
Revisions
-
kgriffs revised this gist
Nov 2, 2022 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -18,7 +18,7 @@ async def worker(shutdown_event): async def do_shutdown(task): # Here we could await join() or whatever # Then also cancel one or more tasks task.cancel() -
kgriffs created this gist
Nov 2, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,40 @@ import asyncio import functools import signal import sys import time async def worker(shutdown_event): try: while True: await asyncio.sleep(1) except asyncio.CancelledError: # catch it so it does not get logged by the asyncio library pass print('Shutting down...') async def do_shutdown(task): # Here we could await join() or whatever # Then also cancel one more more tasks task.cancel() async def listener(): shutdown_event = asyncio.Event() task = asyncio.create_task(worker(shutdown_event)) asyncio.get_running_loop().add_signal_handler( signal.SIGINT, functools.partial(asyncio.create_task, do_shutdown(task)) ) await task # Not really necessary in this example since asyncio.run() will return # once listener() returns and then the script ends. sys.exit(0) asyncio.run(listener())