Advanced Python Scheduler (APScheduler)

3.11.2 · active · verified Sun Mar 29

APScheduler is a flexible, in-process task scheduler library for Python, offering cron-like capabilities. It allows you to schedule Python code to be executed later, either once or periodically, within your application. The current stable version is 3.11.2. It supports various scheduler types, job stores (e.g., in-memory, SQLAlchemy, MongoDB), and triggers (date, interval, cron, calendarinterval). APScheduler is primarily meant to be run inside existing applications, not as a standalone daemon. It is actively maintained with a stable 3.x series and an ongoing pre-release 4.x series with significant architectural changes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a `BackgroundScheduler` which runs jobs in a separate thread without blocking the main application. It schedules a simple function to run every 5 seconds using an `IntervalTrigger`. The `while True: time.sleep(2)` loop keeps the main thread alive, allowing the background scheduler to operate. A `KeyboardInterrupt` handler ensures a graceful shutdown of the scheduler.

import time
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

def my_job():
    print(f"Hello from APScheduler! The time is: {datetime.now()}")

if __name__ == '__main__':
    scheduler = BackgroundScheduler()
    scheduler.add_job(my_job, IntervalTrigger(seconds=5), id='my_scheduled_job')
    
    print('Starting scheduler. Press Ctrl+C to exit.')
    scheduler.start()

    try:
        # This is here to simulate application activity (for BackgroundScheduler)
        while True:
            time.sleep(2)
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
        print("Scheduler shut down successfully.")

view raw JSON →