aiocron: Crontabs for asyncio

2.1 · active · verified Thu Apr 16

aiocron is a Python library that enables scheduling asynchronous functions using crontab-like syntax within an asyncio event loop. It provides a decorator for coroutines, making it straightforward to define recurring tasks. Currently at version 2.1, the library has a moderate release cadence, with notable breaking changes between its 1.x and 2.x major versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to schedule an asynchronous function to run every minute using the `@aiocron.crontab` decorator. The `main` function sets up the scheduler and then keeps the asyncio event loop running indefinitely with `asyncio.get_event_loop().run_forever()` to ensure tasks are executed.

import aiocron
import asyncio
import datetime

async def my_scheduled_task():
    """A simple asynchronous task."""
    current_time = datetime.datetime.now().strftime('%H:%M:%S')
    print(f"Hello from scheduled task! Current time: {current_time}")

async def main():
    # Schedule 'my_scheduled_task' to run every minute using the crontab decorator.
    # By default, start=True, so it begins scheduling immediately.
    @aiocron.crontab('* * * * *')
    async def run_my_task():
        await my_scheduled_task()

    print("aiocron scheduler started. Task 'run_my_task' will run every minute.")
    # Keep the asyncio event loop running indefinitely for scheduled tasks.
    await asyncio.get_event_loop().run_forever()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nScheduler stopped by user.")

view raw JSON →