Aiorun

2025.1.1 · active · verified Thu Apr 16

Aiorun is a Python library that simplifies the creation of `asyncio` applications by providing a `run()` function to manage common boilerplate for startup and graceful shutdown. It automatically handles event loop creation, task scheduling, and signal handling for `SIGINT` and `SIGTERM` (or CTRL-C/CTRL-BREAK on Windows). Aiorun is actively maintained, with a versioning scheme that often reflects the year of release.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic `aiorun` application with two simulated long-running tasks. It shows how to schedule tasks and includes `asyncio.CancelledError` handling within a task to perform cleanup during a graceful shutdown initiated by a signal (like `Ctrl+C`). The `aiorun.run(main())` call manages the event loop lifecycle and signal processing.

import asyncio
from aiorun import run

async def my_long_running_task(name, duration):
    try:
        print(f"Task {name}: Starting for {duration} seconds...")
        for i in range(duration):
            await asyncio.sleep(1)
            print(f"Task {name}: {i + 1}/{duration} seconds passed.")
        print(f"Task {name}: Completed normally.")
    except asyncio.CancelledError:
        print(f"Task {name}: Was cancelled, performing cleanup...")
    finally:
        print(f"Task {name}: Exiting.")

async def main():
    print("Main application starting...")
    # Schedule multiple tasks
    asyncio.create_task(my_long_running_task("Alpha", 5))
    asyncio.create_task(my_long_running_task("Beta", 10))
    
    # Keep main running until a shutdown signal is received
    # In aiorun, you don't typically need loop.run_forever() directly
    # The 'run()' function itself manages the loop until a signal.
    print("Main application tasks scheduled. Waiting for shutdown signal (e.g., Ctrl+C)...")

if __name__ == '__main__':
    # aiorun.run() starts the event loop and handles graceful shutdown
    # It expects an awaitable (coroutine or task) to start the application logic.
    try:
        run(main())
    except KeyboardInterrupt:
        print("\nApplication terminated by KeyboardInterrupt (Ctrl+C).")
    print("Application shutdown complete.")

view raw JSON →