Skip to main content

aioshutdown

Context manager that provides simple graceful shutdown interface for your asyncio tasks.

Installation

pip install -U aioshutdown

Usage

Just specify the list of signals that you want to intercept using the | operator:

from aioshutdown import SIGTERM, SIGINT, SIGHUP


with SIGTERM | SIGHUP | SIGINT as loop:
    ...

The context manager will return an instance of the current event loop. You can intercept signals directly inside your coroutines:

async def my_task(sleep: int):
    try:
        """ Main logic of your coroutine. """
    except asyncio.CancelledError as exc:
        """ In this place you can gracefully complete the work. """

Full example:

import asyncio
from aioshutdown import SIGTERM, SIGINT, SIGHUP
import logging


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s",
    datefmt="%H:%M:%S",
)

async def my_task(sleep: int):
    try:
        while True:
            logging.info("Sleep from task #%s", sleep)
            await asyncio.sleep(sleep)
    except asyncio.CancelledError as exc:
        # Received an exit signal. In this place we gracefully complete the work.
        signal = exc.args[0] # NOTE: works in Python >= 3.9 only: https://docs.python.org/3/library/asyncio-future.html?highlight=Changed%20in%20version%203.9:%20Added%20the%20msg%20parameter.#asyncio.Future.cancel
        logging.warning("Received %s signal. Shutting down...", signal.value)

# Usage with `run_forever`

with SIGTERM | SIGHUP | SIGINT as loop:
    tasks = [loop.create_task(my_task(i)) for i in range(1, 10)]
    loop.run_forever()

# Usage with `run_until_complete`

with SIGTERM | SIGHUP | SIGINT as loop:
    tasks = [loop.create_task(my_task(i)) for i in range(1, 10)]
    loop.run_until_complete(asyncio.gather(*results))

Output

23:04:05,798 INFO: Sleep from task #1
23:04:05,798 INFO: Sleep from task #2
23:04:06,799 INFO: Sleep from task #1
23:04:07,800 INFO: Sleep from task #2
23:04:07,800 INFO: Sleep from task #1
23:04:08,801 INFO: Sleep from task #1
^C23:04:09,504 INFO: Received exit signal SIGINT...
23:04:09,504 INFO: Cancelling 2 outstanding tasks
23:04:09,504 WARNING: Received 2 signal. Shutting down...
23:04:09,504 WARNING: Received 2 signal. Shutting down...
23:04:09,504 INFO: Stopping event loop

Useful links

Graceful Shutdowns with asyncio

Metadata

Release files for aioshutdown 0.0.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aioshutdown 0.0.4
File Size Uploaded
aioshutdown-0.0.4.tar.gz 5.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for aioshutdown 0.0.4
File Interpreter ABI Platform
aioshutdown-0.0.4-py3-none-any.whl Python 3 none any Details

Total release size: 10.5 kB

Release files / aioshutdown-0.0.4.tar.gz

Download URL aioshutdown-0.0.4.tar.gz
Size 5.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e0627700fbf6388d3ab4faccf7204e78eb4a1c78caa9236d5e429967df7e2f80
BLAKE2b-256 checksum
How to use checksums
9ab5f4d1fb8063c67781eb5468c4125f2b3f651c834ca8886f03743f93b6f466
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.8.18

Release files / aioshutdown-0.0.4-py3-none-any.whl

Download URL aioshutdown-0.0.4-py3-none-any.whl
Size 5.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b70d4e63f3a01184af4cf404d175c74a94cc033db623722ed0e4da908cf56338
BLAKE2b-256 checksum
How to use checksums
c4090480a8bb9eb22621f1f3f26004c7fab1ce40e01ff7c35493aab33361f525
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.8.18

Release history Release notifications | RSS feed

This release

0.0.4 This release

2 release files

0.0.3

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page