Skip to content

Instantly share code, notes, and snippets.

@kgriffs
Last active November 2, 2022 01:52
Show Gist options
  • Save kgriffs/d827db257815701a30c1a03a66e6d09f to your computer and use it in GitHub Desktop.
Save kgriffs/d827db257815701a30c1a03a66e6d09f to your computer and use it in GitHub Desktop.

Revisions

  1. kgriffs revised this gist Nov 2, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion example_asyncio_signal_shutdown.py
    Original 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 more more tasks
    # Then also cancel one or more tasks
    task.cancel()


  2. kgriffs created this gist Nov 2, 2022.
    40 changes: 40 additions & 0 deletions example_asyncio_signal_shutdown.py
    Original 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())