aiojobs

1.4.0 · active · verified Thu Apr 16

aiojobs is an asyncio-based job scheduler for managing background tasks. It allows spawning and tracking long-running coroutines, handling their cancellation, and ensuring graceful shutdown. The current version is 1.4.0, and it follows an active release cadence with minor updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a `Scheduler` using the `async with` context (recommended for graceful shutdown since v1.3.0), spawn background tasks using `scheduler.spawn()`, and optionally wait for individual jobs to complete with `job.wait()`.

import asyncio
from aiojobs import Scheduler

async def worker(task_id: int):
    print(f"Worker {task_id}: Starting...")
    try:
        await asyncio.sleep(2) # Simulate work
        print(f"Worker {task_id}: Finished.")
    except asyncio.CancelledError:
        print(f"Worker {task_id}: Cancelled during sleep.")

async def main():
    # Use async with for graceful shutdown (introduced in v1.3.0)
    async with Scheduler() as scheduler:
        print("Scheduler created.")

        job1 = await scheduler.spawn(worker(1))
        job2 = await scheduler.spawn(worker(2))

        print(f"Spawned jobs: {scheduler.pending_count}")

        # Wait for job1 to complete (optional)
        await job1.wait()
        print(f"Job 1 status: {job1.closed}")

    print("Scheduler closed. All pending tasks should be done or cancelled.")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →