# Python job scheduler libraries

Python job scheduler libraries run functions at set times or intervals and hand longer work to background workers. A task queue sends each job through a broker such as Redis to separate worker processes. These libraries let web apps and AI agents run recurring work such as reports and data syncs.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [Celery](#celery) | 53.6M | 29.2K | Nov 2026 | BSD-3-Clause |
| [APScheduler](#apscheduler) | 44.5M | 7.7K | Jun 2026 | MIT |
| [Huey](#huey) | 15.5M | 6.1K | Nov 2026 | MIT |
| [RQ](#rq) | 13.1M | 10.7K | Oct 2026 | BSD-2-Clause |
| [schedule](#schedule) | 6.9M | 12.3K | May 2024 | MIT |
| [arq](#arq) | 5.6M | 3.0K | Apr 2026 | MIT |
| [Taskiq](#taskiq) | 2.6M | 2.4K | Sep 2026 | MIT |
| [Dramatiq](#dramatiq) | 2.5M | 5.3K | Sep 2026 | LGPL-3.0-or-later |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[Celery](#celery) has the most monthly downloads in this comparison, at 53.6M.

## Capabilities

| Library | Recurring schedule support | Separate task workers |
| --- | --- | --- |
| [Celery](#celery) | Yes | Yes |
| [APScheduler](#apscheduler) | Yes | No |
| [Huey](#huey) | Yes | Yes |
| [RQ](#rq) | Yes | Yes |
| [schedule](#schedule) | Yes | No |
| [arq](#arq) | Yes | Yes |
| [Taskiq](#taskiq) | Yes | Yes |
| [Dramatiq](#dramatiq) | Via plugin | Yes |

## Libraries

### Celery

[GitHub](https://github.com/celery/celery) · [PyPI](https://pypi.org/project/celery) · [Docs](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html)

Schedules periodic tasks with beat and executes them on worker nodes.

- Downloads / mo: 53.6M
- Stars: 29.2K
- Last release: 5.7.0
- License: BSD-3-Clause
- Capabilities: [From the Celery docs](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html)

**Strengths**

- **Separates scheduling from task execution.** Let beat enqueue periodic tasks for worker nodes to execute.
- **Supports cron-style periodic schedules.** Use crontab schedules for tasks that run at chosen calendar times.

**Watch out for**

- **Each schedule needs one beat.** Run one scheduler for each schedule to avoid duplicate task submissions.
- **Periodic tasks can overlap.** Use a lock when a periodic task can outlast its interval.

```sh
python -m pip install "celery[redis]==5.7.0"
```

**readthedocs/readthedocs.org** (8.4K stars)

[readthedocs/readthedocs.org](https://github.com/readthedocs/readthedocs.org) 

```python
def finish_import_project(self, request, project):
    """
    Perform last steps to import a project into Read the Docs.

    - Add the user from request as maintainer
    - Run extra tasks that are needed before building the project
    - Trigger the initial build

    Direct upload projects skip the last two steps:
    Read the Docs never builds them, and the webhook and SSH key are not needed.

    It requires the Project was already saved into the DB.

    :param request: Django Request object
    :param project: Project instance just imported (already saved)
    """
    project.users.add(request.user)
    log.info(
        "Project imported.",
        project_slug=project.slug,
        user_username=request.user.username,
    )

    if project.is_direct_upload:
        return None

    update_docs, build = prepare_build(project)
    if (update_docs, build) == (None, None):
        return None

    tasks = self._get_post_import_tasks(project, request.user)
    # Build-isolated builds are dispatched by ``admit_queued_builds``,
    # running ``update_docs`` too would build it twice on two builders.
    if not project.has_feature(Feature.USE_BUILD_ISOLATED):
        tasks.append(update_docs)
    if tasks:
        chain(*tasks).apply_async()

```

[readthedocs/projects/views/mixins.py](https://github.com/readthedocs/readthedocs.org/blob/38dd30b02babe5890d38d2bb488f08cfeb97cf3c/readthedocs/projects/views/mixins.py#L99-L135) · [More projects using Celery →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20celery%20for%20async%20scheduler%20cleanup%2C%20worker-pool%20startup%20and%20model-backed%20periodic%20due%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
# tasks.py
from celery import Celery

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

@app.task
def add(x, y):
    return x + y

# producer.py
import tasks

result = tasks.add.delay(1, 2)

```

From [periodic-tasks.html](https://docs.celeryq.dev/en/stable/getting-started/first-steps-with-celery.html)

### APScheduler

[GitHub](https://github.com/agronholm/apscheduler) · [PyPI](https://pypi.org/project/APScheduler) · [Docs](https://apscheduler.readthedocs.io/en/3.x/userguide.html)

Schedules Python jobs with date, interval, and cron triggers inside an application.

- Downloads / mo: 44.5M
- Stars: 7.7K
- Last release: 3.11.3
- License: MIT
- Capabilities: [From the APScheduler docs](https://apscheduler.readthedocs.io/en/3.x/userguide.html)

**Strengths**

- **Runs inside an existing application.** Use a background or asyncio scheduler within the application process.
- **Exports jobs as JSON.** Move saved jobs between job stores through an exported JSON document.

**Watch out for**

- **Job stores cannot be shared.** Give each scheduler its own job store rather than sharing it across processes.
- **Persistent jobs need importable functions.** Use globally accessible callables and serializable arguments with persistent job stores.

```sh
python -m pip install APScheduler==3.11.3
```

**python-telegram-bot/python-telegram-bot** (29.6K stars)

[python-telegram-bot/python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) 

```python
def __init__(self) -> None:
    if not APS_AVAILABLE:
        raise RuntimeError(
            "To use `JobQueue`, PTB must be installed via `pip install "
            '"python-telegram-bot[job-queue]"`.'
        )

    self._application: weakref.ReferenceType[Application] | None = None
    self._executor = AsyncIOExecutor()
    self.scheduler: "AsyncIOScheduler" = AsyncIOScheduler(  # noqa: UP037
        **self.scheduler_configuration
    )

```

[src/telegram/ext/_jobqueue.py](https://github.com/python-telegram-bot/python-telegram-bot/blob/41e3633bd1b4e51693ee57059828a59a9773618a/src/telegram/ext/_jobqueue.py#L116-L127) · [More projects using APScheduler →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20APScheduler%20for%20async%20scheduler%20cleanup%2C%20worker-pool%20startup%20and%20model-backed%20periodic%20due%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from apscheduler.schedulers.blocking import BlockingScheduler

def tick():
    print("tick")

scheduler = BlockingScheduler()
scheduler.add_job(tick, "interval", seconds=60)
scheduler.start()

```

From [background.py](https://apscheduler.readthedocs.io/en/3.x/userguide.html)

### Huey

[GitHub](https://github.com/coleifer/huey) · [PyPI](https://pypi.org/project/huey) · [Docs](https://huey.readthedocs.io/en/latest/guide.html)

Runs a small task queue.

- Downloads / mo: 15.5M
- Stars: 6.1K
- Last release: 3.5.4
- License: MIT
- Capabilities: [From the Huey docs](https://huey.readthedocs.io/en/latest/guide.html)

```sh
python -m pip install huey==3.5.4
```

**Quickstart**

```python
# tasks.py
from huey import SqliteHuey

huey = SqliteHuey("demo", filename="huey.db")

@huey.task()
def add(x, y):
    return x + y

# producer.py
import tasks

result = tasks.add(1, 2)

```

From [guide.html](https://huey.readthedocs.io/en/latest/guide.html) · [Find projects using Huey →](https://dashboard.exa.ai/playground/search?q=huey%20GitHub%20projects)

### RQ

[GitHub](https://github.com/rq/rq) · [PyPI](https://pypi.org/project/rq) · [Docs](https://python-rq.org/docs/)

Queues jobs for background workers backed by Redis or Valkey.

- Downloads / mo: 13.1M
- Stars: 10.7K
- Last release: 3.0.0
- License: BSD-2-Clause
- Capabilities: [From the RQ docs](https://python-rq.org/docs/)

**Strengths**

- **Schedules jobs through queue APIs.** Use enqueue_at or enqueue_in for execution at a later time.
- **Repeats successful background jobs.** Configure repeat counts and intervals on queued jobs.

**Watch out for**

- **Failed jobs need retry configuration.** Use retries separately when a failed repeating job should run again.
- **Cron scheduling is still beta.** Treat CronScheduler as beta when choosing a recurring production scheduler.

```sh
python -m pip install rq==3.0.0
```

**frappe/frappe** (11.1K stars)

[frappe/frappe](https://github.com/frappe/frappe) 

```python
def start_worker_pool(
	queue: str | None = None,
	num_workers: int = 1,
	quiet: bool = False,
	burst: bool = False,
) -> NoReturn:
	"""Start worker pool with specified number of workers.

	WARNING: This feature is considered "EXPERIMENTAL".
	"""
	_start_sentry()

	# If gc.freeze is done then importing modules before forking allows us to share the memory
	import filelock  # monitor.flush() takes a filelock inside the forked work horse

	import frappe.database.query  # sqlparse and indirect imports
	import frappe.query_builder  # pypika
	import frappe.utils  # common utils
	import frappe.utils.safe_exec
	import frappe.utils.scheduler
	import frappe.utils.typing_validations  # any whitelisted method uses this
	import frappe.website.path_resolver  # all the page types and resolver
	# end: module pre-loading

	redis_connection = get_redis_conn()

	if queue:
		queue = [q.strip() for q in queue.split(",")]
	queues = get_queue_list(queue, build_queue_name=True)

	if os.environ.get("CI"):
		setup_loghandlers("ERROR")

	set_niceness()
	logging_level = "INFO"
	if quiet:
		logging_level = "WARNING"

	# TODO: Make this true by default eventually. It's limited to RQ WorkerPool
	if sbool(os.environ.get("FRAPPE_BACKGROUND_WORKERS_NOFORK", False)):
		worker_klass = FrappeWorkerNoFork
	else:
		import multiprocessing

		multiprocessing.set_start_method("fork", force=True)
		worker_klass = FrappeWorker

	pool = WorkerPool(
		queues=queues,
		connection=redis_connection,
		num_workers=num_workers,
		worker_class=worker_klass,
	)
	pool.start(logging_level=logging_level, burst=burst)

```

[frappe/utils/background_jobs.py](https://github.com/frappe/frappe/blob/151dc461cc90409b0fb75b36b34a619bdaa95f45/frappe/utils/background_jobs.py#L523-L576) · [More projects using RQ →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20rq%20for%20async%20scheduler%20cleanup%2C%20worker-pool%20startup%20and%20model-backed%20periodic%20due%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from redis import Redis
from rq import Queue

queue = Queue(connection=Redis())
job = queue.enqueue("math.floor", 2.7)

```

From [docs.md](https://python-rq.org/docs/)

### schedule

[GitHub](https://github.com/dbader/schedule) · [PyPI](https://pypi.org/project/schedule) · [Docs](https://schedule.readthedocs.io/en/stable/)

Runs Python callables periodically through an in-process scheduling loop.

- Downloads / mo: 6.9M
- Stars: 12.3K
- Last release: 1.2.2
- License: MIT
- Capabilities: [From the schedule docs](https://schedule.readthedocs.io/en/stable/)

**Strengths**

- **Schedules recurring Python callables.** Express periodic jobs through intervals, weekdays, and time-of-day helpers.
- **Avoids extra scheduler processes.** Run the scheduling loop inside the application without external package dependencies.

**Watch out for**

- **Schedules disappear after restart.** Register jobs again when the application starts.
- **Long jobs delay the loop.** Move long-running work off the main scheduling thread.

```sh
python -m pip install schedule==1.2.2
```

**freqtrade/freqtrade** (57.0K stars)

[freqtrade/freqtrade](https://github.com/freqtrade/freqtrade) 

```python
def __init__(self, config: Config) -> None:
    """
    Init all variables and objects the bot needs to work
    :param config: configuration dict, you can use Configuration.get_config()
    to get the config dict.
    """
    self.active_pair_whitelist: list[str] = []

    # Init bot state
    self.state = State.STOPPED

    # Init objects
    self.config = config
    exchange_config: ExchangeConfig = deepcopy(config["exchange"])
    # Remove credentials from original exchange config to avoid accidental credential exposure
    remove_exchange_credentials(config["exchange"], True)

    self.exchange = ExchangeResolver.load_exchange(
        self.config, exchange_config=exchange_config, load_leverage_tiers=True
    )

    self.strategy: IStrategy = StrategyResolver.load_strategy(self.config)

    # Check config consistency here since strategies can set certain options
    validate_config_consistency(config)
    # Re-validate exchange compatibility
    self.exchange.validate_config(self.config)

    init_db(self.config["db_url"])

    self.wallets = Wallets(self.config, self.exchange)

    PairLocks.timeframe = self.config["timeframe"]

    self.trading_mode: TradingMode = self.config.get("trading_mode", TradingMode.SPOT)
    self.margin_mode: MarginMode = self.config.get("margin_mode", MarginMode.NONE)
    self.last_process: datetime | None = None

    # RPC runs in separate threads, can start handling external commands just after
    # initialization, even before Freqtradebot has a chance to start its throttling,
    # so anything in the Freqtradebot instance should be ready (initialized), including
    # the initial state of the bot.
    # Keep this at the end of this initialization method.
    self.rpc: RPCManager = RPCManager(self)

    self.dataprovider = DataProvider(self.config, self.exchange, rpc=self.rpc)
    self.pairlists = PairListManager(self.exchange, self.config, self.dataprovider)

    self.dataprovider.add_pairlisthandler(self.pairlists)

    # Attach Dataprovider to strategy instance
    self.strategy.dp = self.dataprovider
    # Attach Wallets to strategy instance
    self.strategy.wallets = self.wallets

    # Init ExternalMessageConsumer if enabled
    self.emc = (
        ExternalMessageConsumer(self.config, self.dataprovider)
        if self.config.get("external_message_consumer", {}).get("enabled", False)
        else None
    )

    logger.info("Starting initial pairlist refresh")
    with MeasureTime(
        lambda duration, _: logger.info(f"Initial Pairlist refresh took {duration:.2f}s"), 0
    ):
        self.active_pair_whitelist = self._refresh_active_whitelist()

    # Set initial bot state from config
    initial_state = self.config.get("initial_state")
    self.state = State[initial_state.upper()] if initial_state else State.STOPPED

    # Protect exit-logic from forcesell and vice versa
    self._exit_lock = Lock()
    timeframe_secs = timeframe_to_seconds(self.strategy.timeframe)
    self._exit_reason_cache = PeriodicCache(100, ttl=timeframe_secs)
    LoggingMixin.__init__(self, logger, timeframe_secs)

    self._schedule = Scheduler()

    if self.trading_mode == TradingMode.FUTURES:

        def update():
            self.update_funding_fees()
            self.update_all_liquidation_prices()
            self.wallets.update()

        # This would be more efficient if scheduled in utc time, and performed at each
        # funding interval, specified by funding_fee_times on the exchange classes
        # However, this reduces the precision - and might therefore lead to problems.
        for time_slot in range(0, 24):
            for minutes in [1, 31]:
                t = str(time(time_slot, minutes, 2))
                self._schedule.every().day.at(t).do(update)

    self._schedule.every().day.at("00:02").do(self.exchange.ws_connection_reset)

    self.strategy.ft_bot_start()
    # Initialize protections AFTER bot start - otherwise parameters are not loaded.
    self.protections = ProtectionManager(self.config, self.strategy.protections)

    def log_took_too_long(duration: float, time_limit: float):
        logger.warning(
            f"Strategy analysis took {duration:.2f}s, more than 25% of the timeframe "
            f"({time_limit:.2f}s). This can lead to delayed orders and missed signals."
            "Consider either reducing the amount of work your strategy performs "
            "or reduce the amount of pairs in the Pairlist."
        )

    self._measure_execution = MeasureTime(log_took_too_long, timeframe_secs * 0.25)

```

[freqtrade/freqtradebot.py](https://github.com/freqtrade/freqtrade/blob/797ea46bb3b62ba8d0ca39b038610d82eea5be28/freqtrade/freqtradebot.py) · [More projects using schedule →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20schedule%20for%20async%20scheduler%20cleanup%2C%20worker-pool%20startup%20and%20model-backed%20periodic%20due%20checks&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
import time
import schedule

def tick():
    print("tick")

schedule.every(10).seconds.do(tick)
while True:
    schedule.run_pending()
    time.sleep(1)

```

From [stable.md](https://schedule.readthedocs.io/en/stable/)

### arq

[GitHub](https://github.com/python-arq/arq) · [PyPI](https://pypi.org/project/arq) · [Docs](https://arq-docs.helpmanual.io/)

Runs job queues in Python with asyncio and Redis.

- Downloads / mo: 5.6M
- Stars: 3.0K
- Last release: 0.28.0
- License: MIT
- Capabilities: [From the arq docs](https://arq-docs.helpmanual.io/)

```sh
python -m pip install arq==0.28.0 "redis>=5.3,<6"
```

**zylon-ai/private-gpt** (57.6K stars)

[zylon-ai/private-gpt](https://github.com/zylon-ai/private-gpt) 

```python
async def _abort_job(*, job_id: str, queue_name: str, timeout: int) -> bool:
    redis = await _get_pool()
    job = Job(
        job_id,
        redis=redis,
        _queue_name=queue_name,
    )
    try:
        return await job.abort(timeout=timeout)
    except TimeoutError:
        logger.warning(
            "Timed out confirming abort for job_id=%s queue=%s",
            job_id,
            queue_name,
        )
        return False

```

[private_gpt/arq/enqueue.py](https://github.com/zylon-ai/private-gpt/blob/9d37a133f1d50e9b10ed527ce198ffd7ded1af70/private_gpt/arq/enqueue.py#L117-L132) · [More projects using arq →](https://dashboard.exa.ai/playground/search?q=arq%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from arq import create_pool
from arq.connections import RedisSettings

async def add(ctx, x, y):
    return x + y

class WorkerSettings:
    functions = [add]

async def main():
    redis = await create_pool(RedisSettings())
    try:
        await redis.enqueue_job("add", 1, 2)
    finally:
        await redis.aclose()

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

```

From [index.html](https://arq-docs.helpmanual.io/)

### Taskiq

[GitHub](https://github.com/taskiq-python/taskiq) · [PyPI](https://pypi.org/project/taskiq) · [Docs](https://taskiq-python.github.io/guide/getting-started.html)

Runs a distributed task queue with full async support.

- Downloads / mo: 2.6M
- Stars: 2.4K
- Last release: 0.13.0
- License: MIT
- Capabilities: [From the Taskiq docs](https://taskiq-python.github.io/guide/getting-started.html)

```sh
python -m pip install taskiq==0.13.0
```

**TeKrop/overfast-api** (199 stars)

[TeKrop/overfast-api](https://github.com/TeKrop/overfast-api) 

```python
async def enqueue(
        self,
        task_name: str,
        *,
        job_id: str | None = None,
    ) -> str:
        """Dispatch a job to the taskiq worker, skipping duplicates.

        Uses ``SET NX`` to atomically claim the dedup slot before kicking the
        task by name (``task_name`` must match a ``@broker.task(task_name=...)``
        in ``app/worker.py``).  If the slot is already taken the call is a no-op.
        The ``job_id`` is passed to the task as its first positional argument.
        """
        effective_id = job_id or task_name

        try:
            claimed = await self._valkey.set(
                f"{JOB_KEY_PREFIX}{effective_id}",
                "pending",
                nx=True,
                ex=settings.worker_job_timeout,
            )
            if not claimed:
                logger.debug("[ValkeyTaskQueue] Already queued: {}", effective_id)
                return effective_id

            await AsyncKicker(task_name, broker, {}).kiq(effective_id)
            if settings.prometheus_enabled:
                background_refresh_triggered_total.labels(
                    entity_type=task_name.removeprefix("refresh_")
                ).inc()
            logger.debug(
                "[ValkeyTaskQueue] Enqueued {} (job_id={})", task_name, effective_id
            )
        except Exception as exc:  # noqa: BLE001
            logger.warning("[ValkeyTaskQueue] Failed to enqueue {}: {}", task_name, exc)

        return effective_id

```

[app/adapters/tasks/valkey_task_queue.py](https://github.com/TeKrop/overfast-api/blob/c9a632a5fe2b257a66eab7c0b3365d451e357a88/app/adapters/tasks/valkey_task_queue.py#L46-L83) · [More projects using Taskiq →](https://dashboard.exa.ai/playground/search?q=taskiq%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from taskiq import InMemoryBroker

broker = InMemoryBroker()

@broker.task
async def add_one(value: int) -> int:
    return value + 1

async def main():
    await broker.startup()
    try:
        task = await add_one.kiq(1)
        result = await task.wait_result(timeout=2)
        print(result.return_value)
    finally:
        await broker.shutdown()

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

```

From [getting-started.html](https://taskiq-python.github.io/guide/getting-started.html)

### Dramatiq

[GitHub](https://github.com/Bogdanp/dramatiq) · [PyPI](https://pypi.org/project/dramatiq) · [Docs](https://dramatiq.io/guide.html)

Processes background tasks in Python.

- Downloads / mo: 2.5M
- Stars: 5.3K
- Last release: 2.2.1
- License: LGPL-3.0-or-later
- Capabilities: [From the Dramatiq docs](https://dramatiq.io/guide.html)

```sh
python -m pip install "dramatiq[redis]==2.2.1"
```

**polarsource/polar** (10.5K stars)

[polarsource/polar](https://github.com/polarsource/polar) 

```python
def get_broker(*, database: bool = True) -> dramatiq.Broker:
    retry = Retry(default_backoff(), retries=50)
    redis_pool = redis.ConnectionPool.from_url(
        settings.redis_url,
        client_name=f"{settings.ENV.value}.worker.dramatiq",
        retry=retry,
        retry_on_error=REDIS_RETRY_ON_ERRROR,
        socket_timeout=10,
        socket_connect_timeout=3,
    )

    result_backend = ResultsBackend(
        encoder=JSONEncoder(),
        client=SyncFailoverRedis(
            connection_pool=redis.ConnectionPool.from_url(
                settings.redis_url,
                retry=retry,
                retry_on_error=REDIS_RETRY_ON_ERRROR,
                socket_timeout=10,
                socket_connect_timeout=3,
            )
        ),
    )
    rate_limiter_backend = RateLimiterBackend(
        client=SyncFailoverRedis(
            connection_pool=redis.ConnectionPool.from_url(
                settings.redis_url,
                retry=retry,
                retry_on_error=REDIS_RETRY_ON_ERRROR,
                socket_timeout=10,
                socket_connect_timeout=3,
            )
        )
    )

    middleware_list = [
        # Infrastructure & async support
        middleware.ShutdownNotifications(),
        MonitoredAsyncIO(),
        # Results backend for pipeline/group support
        Results(backend=result_backend, result_ttl=60_000),
        # Group completion callbacks for orchestrating task sequences
        GroupCallbacks(rate_limiter_backend),
        # Resource lifecycle (worker boot/shutdown)
        *([SQLAlchemyMiddleware()] if database else []),
        RedisMiddleware(),
        HTTPXMiddleware(),
        HealthMiddleware(database=database),
        scheduler_middleware,
        # Observability (outer layer for message processing)
        LogContextMiddleware(),
        LogfireMiddleware(),
        PrometheusMiddleware(),
        # Message flow control
        DebounceMiddleware(redis_pool),
        # Retry & execution control (MaxRetries must precede Retries)
        OperationalErrorMiddleware(),
        MaxRetriesMiddleware(),
        middleware.Retries(
            max_retries=settings.WORKER_MAX_RETRIES,
            min_backoff=settings.WORKER_MIN_BACKOFF_MILLISECONDS,
        ),
        middleware.AgeLimit(),
        middleware.TimeLimit(time_limit=TASK_TIME_LIMIT_DEFAULT_MS),
        middleware.CurrentMessage(),
    ]

    broker = RoutingRedisBroker(
        connection_pool=redis_pool,
        client=SyncFailoverRedis(connection_pool=redis_pool),
        middleware=middleware_list,
        dead_message_ttl=3600 * 1000,  # 1 hour in milliseconds
    )

    return broker

```

[server/polar/worker/_broker.py](https://github.com/polarsource/polar/blob/b5adc13284ed5aca994a1959543b08187ce2cabc/server/polar/worker/_broker.py#L213-L287) · [More projects using Dramatiq →](https://dashboard.exa.ai/playground/search?q=dramatiq%20GitHub%20projects)

**Quickstart**

```python
# tasks.py
import dramatiq
from dramatiq.brokers.redis import RedisBroker

dramatiq.set_broker(RedisBroker(url="redis://localhost:6379/0"))

@dramatiq.actor
def add(x, y):
    return x + y

# producer.py
import tasks

message = tasks.add.send(1, 2)

```

From [guide.html](https://dramatiq.io/guide.html)

## FAQ

### Which Python job scheduler should I use?

[APScheduler](#apscheduler) suits cron, interval, and one-off jobs inside a running application. [Celery](#celery) suits periodic tasks that run on separate workers. [schedule](#schedule) suits small scripts with an in-process polling loop.

### What is APScheduler?

[APScheduler](#apscheduler) schedules Python jobs with date, interval, and cron triggers inside an application. Optional job stores keep jobs across restarts.

### What is Celery beat?

Celery beat is the scheduler that submits periodic tasks to [Celery](#celery) workers at set intervals or cron times.

### What is Dramatiq?

[Dramatiq](#dramatiq) is a background task processing library that runs Python functions on workers through a message broker.

### How do I run a cron job in Python?

[APScheduler](#apscheduler) runs cron-style triggers inside a Python process. [Celery](#celery) beat and the [RQ](#rq) CronScheduler run them for jobs that execute on separate workers.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python job scheduler libraries APScheduler schedule Celery RQ cron recurring jobs code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
