Convert Figma logo to code with AI

agronholm logoapscheduler

Task scheduling library for Python

6,370
714
6,370
42

Top Related Projects

11,889

Python job scheduling for humans.

25,320

Distributed Task Queue (development branch)

6,518

Real-time monitor and web admin for Celery distributed task queue

9,995

Simple job queues for Python

13,186

a cron library for go

1,175

Crontab jobs management in Python

Quick Overview

APScheduler (Advanced Python Scheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. It's designed to be flexible, feature-rich, and can integrate with various frameworks and scheduling scenarios.

Pros

  • Versatile scheduling options (date, interval, cron-style)
  • Supports multiple job stores (memory, SQLAlchemy, MongoDB, Redis)
  • Can be integrated with popular frameworks (Flask, Django, Tornado)
  • Robust error handling and logging capabilities

Cons

  • Learning curve can be steep for complex scheduling scenarios
  • Documentation could be more comprehensive for advanced use cases
  • Some users report issues with long-running jobs in certain configurations
  • Limited built-in support for distributed environments

Code Examples

  1. Basic interval scheduling:
from apscheduler.schedulers.background import BackgroundScheduler

def job_function():
    print("Hello, APScheduler!")

scheduler = BackgroundScheduler()
scheduler.add_job(job_function, 'interval', seconds=10)
scheduler.start()
  1. Cron-style scheduling:
from apscheduler.schedulers.blocking import BlockingScheduler

def daily_task():
    print("This job runs every day at 9:00 AM")

scheduler = BlockingScheduler()
scheduler.add_job(daily_task, 'cron', hour=9)
scheduler.start()
  1. One-time job scheduling:
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta

def future_task():
    print("This job runs once, 1 hour from now")

scheduler = BackgroundScheduler()
run_time = datetime.now() + timedelta(hours=1)
scheduler.add_job(future_task, 'date', run_date=run_time)
scheduler.start()

Getting Started

To get started with APScheduler, first install it using pip:

pip install apscheduler

Then, you can create a simple scheduled job like this:

from apscheduler.schedulers.background import BackgroundScheduler
import time

def my_job():
    print("Job executed!")

scheduler = BackgroundScheduler()
scheduler.add_job(my_job, 'interval', seconds=5)
scheduler.start()

try:
    # This is here to simulate application activity (which keeps the main thread alive).
    while True:
        time.sleep(2)
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()

This example creates a background scheduler that runs my_job every 5 seconds. The scheduler runs in a separate thread, allowing your main program to continue execution.

Competitor Comparisons

11,889

Python job scheduling for humans.

Pros of Schedule

  • Lightweight and simple to use, with a clean and intuitive API
  • No external dependencies, making it easy to integrate into projects
  • Human-readable syntax for defining job schedules

Cons of Schedule

  • Limited functionality compared to APScheduler, lacking features like persistent job stores
  • No built-in support for distributed scheduling or advanced execution options
  • Less flexibility in defining complex scheduling patterns

Code Comparison

Schedule:

import schedule
import time

def job():
    print("I'm working...")

schedule.every(10).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

APScheduler:

from apscheduler.schedulers.blocking import BlockingScheduler

def job():
    print("I'm working...")

scheduler = BlockingScheduler()
scheduler.add_job(job, 'interval', minutes=10)
scheduler.start()

Both libraries offer straightforward ways to schedule jobs, but APScheduler provides more advanced features and configuration options. Schedule focuses on simplicity and readability, while APScheduler offers greater flexibility and power for complex scheduling needs.

25,320

Distributed Task Queue (development branch)

Pros of Celery

  • Distributed task queue system, allowing for scalable and distributed processing
  • Supports multiple message brokers (RabbitMQ, Redis, etc.) for flexibility
  • Rich ecosystem with extensive documentation and community support

Cons of Celery

  • Steeper learning curve and more complex setup compared to APScheduler
  • Requires additional infrastructure (message broker) to function
  • Can be overkill for simpler scheduling needs

Code Comparison

APScheduler:

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
scheduler.add_job(my_job, 'interval', hours=2)
scheduler.start()

Celery:

from celery import Celery

app = Celery('tasks', broker='redis://localhost:6379')

@app.task
def my_task():
    # Task logic here

APScheduler is more straightforward for simple scheduling tasks, while Celery requires more setup but offers powerful distributed task processing capabilities. APScheduler is ideal for in-process scheduling, whereas Celery excels in distributed environments with complex task workflows. Choose based on your project's scalability needs and complexity requirements.

6,518

Real-time monitor and web admin for Celery distributed task queue

Pros of Flower

  • Specialized for monitoring and managing Celery distributed task queues
  • Provides a web-based user interface for real-time task monitoring
  • Offers detailed task statistics and performance metrics

Cons of Flower

  • Limited to Celery task queues, less versatile than APScheduler
  • Requires additional setup and configuration for Celery integration
  • May have higher resource overhead due to web interface

Code Comparison

Flower (monitoring Celery tasks):

from celery import Celery
from flower.command import FlowerCommand

app = Celery('tasks')
FlowerCommand(app=app).run()

APScheduler (scheduling jobs):

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
scheduler.add_job(my_job, 'interval', hours=2)
scheduler.start()

Summary

Flower is a specialized tool for monitoring Celery task queues with a web interface, while APScheduler is a more versatile job scheduling library. Flower excels in providing real-time insights for Celery tasks, but is limited to that ecosystem. APScheduler offers broader scheduling capabilities across various platforms and job types, making it more suitable for general-purpose scheduling needs.

9,995

Simple job queues for Python

Pros of RQ

  • Simpler to set up and use, with a focus on Redis-based job queues
  • Better suited for distributed task processing across multiple workers
  • Includes a web-based dashboard for monitoring and managing jobs

Cons of RQ

  • Less flexible scheduling options compared to APScheduler
  • Limited to Redis as the backend, while APScheduler supports various storage options
  • Lacks some advanced features like job chaining and error handling

Code Comparison

RQ:

from redis import Redis
from rq import Queue

q = Queue(connection=Redis())
result = q.enqueue(my_function, args=(1, 2), kwargs={'c': 3})

APScheduler:

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
scheduler.add_job(my_function, 'interval', minutes=5, args=[1, 2], kwargs={'c': 3})
scheduler.start()

RQ is more focused on queueing and distributing tasks, while APScheduler provides more advanced scheduling capabilities. RQ is ideal for distributed systems with Redis, whereas APScheduler offers greater flexibility in scheduling and storage options. The choice between the two depends on specific project requirements and infrastructure preferences.

13,186

a cron library for go

Pros of cron

  • Lightweight and simple to use, with a focus on cron-style scheduling
  • Designed specifically for Go, integrating well with Go's concurrency model
  • Efficient parsing of cron expressions

Cons of cron

  • Limited to cron-style scheduling, less flexible than APScheduler
  • Fewer built-in features compared to APScheduler's rich functionality
  • Lacks some advanced features like persistent job stores

Code Comparison

cron:

c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.Start()

APScheduler:

scheduler = BlockingScheduler()
scheduler.add_job(my_job, 'cron', hour='*', minute='30')
scheduler.start()

Summary

cron is a lightweight, Go-specific scheduling library focused on cron-style job scheduling. It's simple to use and integrates well with Go's concurrency model. However, it lacks some of the advanced features and flexibility offered by APScheduler.

APScheduler, on the other hand, is a more comprehensive Python scheduling library with support for various job stores, executors, and scheduling methods. It offers greater flexibility and advanced features but may be overkill for simple cron-style scheduling needs.

Choose cron for straightforward cron-based scheduling in Go projects, and APScheduler for more complex scheduling requirements in Python applications.

1,175

Crontab jobs management in Python

Pros of Plan

  • Simpler and more lightweight, focusing on cron-style scheduling
  • Integrates well with Flask applications
  • Provides a clean and intuitive API for defining tasks

Cons of Plan

  • Less feature-rich compared to APScheduler
  • Limited to cron-style scheduling, lacking interval and one-time job support
  • Not as actively maintained, with fewer updates and contributions

Code Comparison

Plan:

from plan import Plan

cron = Plan()

@cron.command('echo hello')
def hello():
    print('hello')

cron.run('write')

APScheduler:

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()

@scheduler.scheduled_job('cron', hour='0-23')
def hello():
    print('hello')

scheduler.start()

Summary

Plan is a simpler, more focused scheduling library that works well for basic cron-style tasks, especially in Flask applications. APScheduler offers a more comprehensive set of features, including various scheduling options and broader platform support. While Plan has a cleaner API for simple use cases, APScheduler provides more flexibility and active development for complex scheduling needs.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

.. image:: https://github.com/agronholm/apscheduler/actions/workflows/test.yml/badge.svg :target: https://github.com/agronholm/apscheduler/actions/workflows/test.yml :alt: Build Status .. image:: https://coveralls.io/repos/github/agronholm/apscheduler/badge.svg?branch=master :target: https://coveralls.io/github/agronholm/apscheduler?branch=master :alt: Code Coverage .. image:: https://readthedocs.org/projects/apscheduler/badge/?version=latest :target: https://apscheduler.readthedocs.io/en/master/?badge=latest :alt: Documentation

.. warning:: The v4.0 series is provided as a pre-release and may change in a backwards incompatible fashion without any migration pathway, so do NOT use this release in production!

Advanced Python Scheduler (APScheduler) is a task scheduler and task queue system for Python. It can be used solely as a job queuing system if you have no need for task scheduling. It scales both up and down, and is suitable for both trivial, single-process use cases as well as large deployments spanning multiple nodes. Multiple schedulers and workers can be deployed to use a shared data store to provide both a degree of high availability and horizontal scaling.

APScheduler comes in both synchronous and asynchronous flavors, making it a good fit for both traditional, thread-based applications, and asynchronous (asyncio or Trio_) applications. Documentation and examples are provided for integrating with either WSGI_ or ASGI_ compatible web applications.

Support is provided for persistent storage of schedules and jobs. This means that they can be shared among multiple scheduler/worker instances and will survive process and node restarts.

The built-in persistent data store back-ends are:

  • PostgreSQL
  • MySQL and derivatives
  • SQLite
  • MongoDB

The built-in event brokers (needed in scenarios with multiple schedulers and/or workers):

  • PostgreSQL
  • Redis
  • MQTT

The built-in scheduling mechanisms (triggers) are:

  • Cron-style scheduling
  • Interval-based scheduling (runs tasks on even intervals)
  • Calendar-based scheduling (runs tasks on intervals of X years/months/weeks/days, always at the same time of day)
  • One-off scheduling (runs a task once, at a specific date/time)

Different scheduling mechanisms can even be combined with so-called combining triggers (see the documentation_ for details).

You can also implement your custom scheduling logic by building your own trigger class. These will be treated no differently than the built-in ones.

Other notable features include:

  • You can limit the maximum number of simultaneous jobs for a given task (function)
  • You can limit the amount of time a job is allowed to start late
  • Jitter (adjustable, random delays added to the run time of each scheduled job)

.. _Trio: https://pypi.org/project/trio/ .. _WSGI: https://wsgi.readthedocs.io/en/latest/what.html .. _ASGI: https://asgi.readthedocs.io/en/latest/index.html .. _documentation: https://apscheduler.readthedocs.io/en/master/

Documentation

Documentation can be found here <https://apscheduler.readthedocs.io/en/master/?badge=latest>_.

Source

The source can be browsed at Github <https://github.com/agronholm/apscheduler>_.

Reporting bugs

A bug tracker <https://github.com/agronholm/apscheduler/issues>_ is provided by GitHub.

Getting help

If you have problems or other questions, you can either:

  • Ask in the apscheduler <https://gitter.im/apscheduler/Lobby>_ room on Gitter
  • Post a question on GitHub discussions_, or
  • Post a question on StackOverflow_ and add the apscheduler tag

.. _GitHub discussions: https://github.com/agronholm/apscheduler/discussions/categories/q-a .. _StackOverflow: http://stackoverflow.com/questions/tagged/apscheduler