0Pricing
FastAPI Backend Development Bootcamp · 课时

使用 Celery Beat 调度周期性作业

使用 Celery Beat 运行重复作业,并在多个工作进程之间安全协调类似 cron 的计划。

使用 Celery Beat 调度周期性作业 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Celery Beat?

Your FastAPI app fires off one-off background tasks with Celery just fine, but some work must run on a schedule: send a digest email every morning, expire abandoned carts every 10 minutes, recompute analytics nightly.

Celery Beat is a scheduler process. It does not execute tasks itself — it wakes up on a tick, decides which tasks are due, and pushes them onto the broker (Redis/RabbitMQ). Your normal celery worker processes pick them up and run them.

  • Beat = the clock that publishes due tasks.
  • Worker = the muscle that runs them.

This separation is the whole reason periodic jobs scale: one Beat, many workers.

Defining the schedule

Schedules live on the Celery app under conf.beat_schedule. Each entry maps a name to a dict with the task path, a schedule (seconds, timedelta, or a crontab), and optional args/kwargs.

The simplest schedule is a fixed interval. Below, the cleanup task runs every 30 seconds. The task path string must match the worker's registered name exactly.

from celery import Celery
from datetime import timedelta

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

@app.task(name="tasks.cleanup_sessions")
def cleanup_sessions():
    # delete expired sessions from the DB
    return "cleaned"

app.conf.beat_schedule = {
    "cleanup-every-30s": {
        "task": "tasks.cleanup_sessions",
        "schedule": timedelta(seconds=30),
    },
}

Cron-style schedules with crontab()

Fixed intervals are coarse. For real calendar logic — "every weekday at 07:30" — use celery.schedules.crontab. It mirrors Unix cron fields: minute, hour, day_of_week, day_of_month, month_of_year.

  • crontab(minute=0, hour=0) — midnight every day.
  • crontab(minute="*/15") — every 15 minutes.
  • crontab(hour=7, minute=30, day_of_week="1-5") — 07:30 Mon–Fri.

Unset fields default to * (every value), exactly like a crontab line.

from celery.schedules import crontab

app.conf.beat_schedule = {
    "morning-digest": {
        "task": "tasks.send_digest",
        "schedule": crontab(hour=7, minute=30, day_of_week="1-5"),
    },
    "quarter-hour-sync": {
        "task": "tasks.sync_inventory",
        "schedule": crontab(minute="*/15"),
    },
}

Passing args and options per entry

Each schedule entry can carry arguments and per-call options. Use args (positional) or kwargs (keyword) to parametrize the same task differently across entries. The options dict lets you route a periodic task to a specific queue, set expires, or override priority.

expires is important for periodic jobs: if Beat enqueues a task but workers are backed up, an expired message is discarded instead of running late and stacking up.

from celery.schedules import crontab

app.conf.beat_schedule = {
    "warm-cache-eu": {
        "task": "tasks.warm_cache",
        "schedule": crontab(minute="*/5"),
        "kwargs": {"region": "eu-west"},
        "options": {"queue": "cache", "expires": 120},
    },
    "warm-cache-us": {
        "task": "tasks.warm_cache",
        "schedule": crontab(minute="*/5"),
        "kwargs": {"region": "us-east"},
        "options": {"queue": "cache", "expires": 120},
    },
}

Registering schedules with a decorator

Instead of one giant beat_schedule dict, you can register entries near the tasks using the on_after_configure signal and app.add_periodic_task. This keeps the schedule co-located with the code it triggers and avoids stale string paths.

add_periodic_task(schedule, signature, name=...) takes the interval or crontab first, then the task signature. You can pass task.s(arg) to bake in arguments.

from celery import Celery
from celery.schedules import crontab

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

@app.task
def rotate_logs(target):
    return f"rotated {target}"

@app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
    sender.add_periodic_task(
        crontab(hour=3, minute=0),
        rotate_logs.s("app.log"),
        name="nightly-log-rotation",
    )

Timezones: the #1 schedule bug

By default Celery interprets crontab times in UTC. If you write crontab(hour=7) expecting local 07:00, your job will fire at the wrong wall-clock time. Always set the timezone explicitly and decide deliberately.

  • timezone — the zone crontab times are evaluated in.
  • enable_utc=True — keep internal timestamps in UTC (recommended) while still evaluating crontabs in your chosen timezone.

Pin the timezone in config so every developer and every server agrees, regardless of the host's local TZ.

app.conf.update(
    timezone="Europe/Istanbul",
    enable_utc=True,
)

# crontab(hour=9, minute=0) now means 09:00 Europe/Istanbul,
# stored/transmitted internally as UTC.

Running Beat and the persistent schedule file

You start the scheduler as its own process. The default scheduler stores its "last run" state in a small file so it does not re-fire everything after a restart.

  • celery -A app beat -l info — run Beat.
  • --schedule /var/run/celerybeat-schedule — where the shelve state file lives.
  • You can run worker + beat together in dev with celery -A app worker -B, but never use -B in production — it ties the clock to one worker's lifecycle.

In production, run exactly one Beat process. Two Beats = every periodic task fires twice.

The single-scheduler rule across workers

You can scale workers horizontally to dozens of pods and Celery handles it: the broker distributes each queued message to exactly one worker. But Beat is the clock, and you must run only one clock.

If two Beat processes run, each independently decides a task is due and publishes it, so subscribers see duplicate executions. Common ways this happens by accident:

  • Two replicas of a pod that both launch beat.
  • Using worker -B and then scaling that worker deployment to 2+.

Fix: a dedicated Beat Deployment with replicas: 1, separate from the worker Deployment you scale freely.

Idempotency: design tasks to survive duplicates

Even with one Beat, duplicates happen — a Beat restart at the wrong second, an at-least-once broker redelivery, or an operator mistake. The robust defense is making periodic tasks idempotent: running twice has the same effect as running once.

A simple pattern is a short-lived distributed lock in Redis using SET NX with an expiry. Whoever acquires the lock does the work; concurrent or duplicate runs skip safely.

import redis

r = redis.Redis(host="localhost", port=6379, db=0)

@app.task(name="tasks.charge_subscriptions")
def charge_subscriptions():
    # acquire a lock valid for 300s; only one runner proceeds
    got = r.set("lock:charge_subscriptions", "1", nx=True, ex=300)
    if not got:
        return "skipped: already running"
    try:
        # ... perform the billing run exactly once ...
        return "charged"
    finally:
        r.delete("lock:charge_subscriptions")

Database-backed schedules with django-celery-beat / RedBeat

The default file scheduler means changing a schedule requires editing code and restarting Beat. For dynamic schedules you want a backend store you can edit at runtime.

  • RedBeat — stores schedules in Redis; great for a Redis-only FastAPI stack. Set beat_scheduler = "redbeat.RedBeatScheduler".
  • django-celery-beat — stores entries in SQL tables, editable via admin UI.

RedBeat also provides a Redis-based lock so that if you accidentally start two Beats, only one is the active scheduler — a safety net for the single-clock rule.

app.conf.update(
    redbeat_redis_url="redis://localhost:6379/1",
    beat_scheduler="redbeat.RedBeatScheduler",
    beat_max_loop_interval=5,
)

A self-contained cron-due check

To build intuition for what Beat does on each tick, here is a tiny standalone simulation: given a list of cron-like jobs (interval in seconds and a last-run timestamp), decide which are due now. This is the core loop Beat performs — compare "now" against "next due" — without any broker.

def due_jobs(now, jobs):
    fired = []
    for name, interval, last_run in jobs:
        if now - last_run >= interval:
            fired.append(name)
    return fired

jobs = [
    ("cleanup", 30, 0),
    ("digest", 3600, 3500),
    ("sync", 900, 100),
]

now = 1000
print(due_jobs(now, jobs))  # ['cleanup', 'sync']

Quick Check: avoiding duplicate periodic runs

You deploy a FastAPI + Celery stack to Kubernetes. To handle load you scale your worker Deployment to 4 replicas, and each worker is started with celery -A app worker -B. Periodic tasks start running 4 times each. What is the correct fix?

Recap

You can now schedule recurring work with Celery Beat:

  • Beat schedules, workers execute — Beat publishes due tasks to the broker; one Beat, many workers.
  • Schedules live in beat_schedule or via add_periodic_task; use timedelta for intervals and crontab() for calendar logic.
  • Per-entry args/options parametrize tasks and set queue/expires to avoid stale pile-ups.
  • Timezones are UTC by default — pin timezone + enable_utc explicitly.
  • One clock only — never worker -B in production; run a single dedicated Beat replica.
  • Idempotency (Redis SET NX locks) protects against duplicate or redelivered runs.
  • RedBeat / django-celery-beat give editable, persistent, lock-protected schedules at runtime.

常见问题解答

「使用 Celery Beat 调度周期性作业」课时是免费的吗?

是的 — 「使用 Celery Beat 调度周期性作业」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「使用 Celery Beat 调度周期性作业」这节课中我会学到什么?

使用 Celery Beat 运行重复作业,并在多个工作进程之间安全协调类似 cron 的计划。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「使用 Celery Beat 调度周期性作业」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 BackgroundTasks 轻量级卸载任务
  2. 将 Celery 工作进程接入 FastAPI 应用
  3. 重试、幂等性与死信处理
  4. 使用 Celery Beat 调度周期性作业
← 返回 FastAPI Backend Development Bootcamp