Scheduled Jobs with Celery Beat: Interval or Crontab, a Stuck-Job Sweep, and Why You Run Exactly One Beat
Beat is only a clock: when an entry is due it puts a ticket on the queue and a worker runs it. Interval counts from Beat's start, crontab reads the clock in UTC. A sweep fails stuck projects, but only if stuck_after is longer than the hard limit. Two Beats sent 12 plus 12 sweeps and two notices; a set-nx lease stops the double work but not the double sends.
What you will learn
- Write a Beat schedule and explain that Beat only sends tickets
- Choose between an interval and a crontab, and remember crontab is UTC by default
- Build a sweep that fails stuck projects, with stuck_after longer than the hard time limit
- Run Beat in its own container with a schedule file, and see what two Beats do
Before you start
- Celery and Redis for background tasks
- Safe to run twice
Some jobs nobody clicks a button for: a sweep that finds stuck projects, a nightly clean-up of old uploads. They run on Celery Beat, and there's one mistake here that's easy to make.
Picture a bakery with one alarm clock for the 6 a.m. bread. It rings, the baker bakes, one batch. Somebody adds a second clock just to be safe. It rings too, and the baker bakes again. The alarm clock is Celery Beat, and a batch is one scheduled job. A second clock isn't a backup. It's a second batch.
Beat is only a clock
celery_app.conf.beat_schedule = {
"sweep-stuck": {
"task": SWEEP_TASK,
"schedule": SWEEP_EVERY,
},
"clean-uploads": {
"task": "clean_uploads",
"schedule": crontab(hour=CLEAN_HOUR, minute=CLEAN_MIN),
},
}
The schedule is just data: a name, a task and when. The sweep-stuck entry names a task and a gap in seconds (300 by default). When it's due, Beat sends a ticket onto the rail and a worker picks it up like any other task. With a 20-second gap, the report showed six sweeps in about two minutes. The clean-uploads entry works the same way. Beat itself never runs a job.
Interval or crontab?
Use an interval for "every few minutes". Use crontab for a time on the clock, and set the timezone for your own night, because crontab hour 2 means 2 in the morning UTC by default.
Finding the stuck project
# longer than the hard time limit of 3660 seconds
STUCK_AFTER = int(os.environ.get("STUCK_AFTER", 3900))
def run_sweep():
worker = socket.gethostname()
cutoff = time.time() - STUCK_AFTER
stuck = store.find_stuck(cutoff)
for project_id in stuck:
time.sleep(MAIL_SECONDS) # stands in for a mail
store.add_notice(project_id, worker)
store.set_status(project_id, "FAILED")
return len(stuck)
A worker was killed five seconds into project p-301. The status still said transcribing, and nobody was left to change it. The sweep (with stuck after set to 20 seconds for the test) found anything transcribing with no update for that long, sent a notice and marked it failed at 22 seconds. Project p-302 was healthy, so it was left alone. Later the killed ticket came back, but the status check at the top of the task saw failed and stopped. (That check is from safe to run twice.)
How long is stuck?
A healthy 40-second job with stuck after set to 20 seconds: the sweep failed it at 26 seconds and sent the notice, and at 40 seconds it said completed. The user got a failure notice for a job that worked. The hard time limit is 3,660 seconds; after it, no job can still be running. So STUCK_AFTER is 3,900. Keep it longer than the hard limit, never shorter.
Beat in its own container
beat:
<<: *app
command: celery -A app.celery_app beat
-l info -s /data/beat-schedule
One service next to the workers. Workers can scale; Beat stays at one. The -s file is Beat's schedule file. With Beat stopped while a job came due, Beat sent that job once on restart when it had the file; without the file, that run was simply lost. So keep the file on a volume. celery worker -B puts a Beat inside a worker, and the docs advise against it in production.
Two Beats, every job twice
Now the mistake on purpose: a second Beat (beat-copy, behind a Compose profile) started one second after the first. Counting the sends with grep over about two minutes: Beat A 12, Beat B 12. The sweep ran 24 times. Project p-401 got two notices, because the copies were one second apart and the mail takes two seconds, so both saw it still transcribing. With one Beat, the same job sent one notice. And both Beats just kept running; nothing warns you. The docs say it plainly: only a single scheduler at a time.
A lock that lets go is the wrong lock
@celery_app.task(name="sweep_released")
def sweep_released():
worker = socket.gethostname()
lock = r.lock("lock:sweep", timeout=LEASE)
if not lock.acquire(blocking=False):
store.log_job("sweep", worker, "skipped")
return "skipped"
try:
store.log_job("sweep", worker, "ran")
return run_sweep()
finally:
lock.release() # the trap: a late copy finds it free
Copy one takes the lock and runs the sweep. Nothing is stuck, so it's over at once, and finally releases the lock. One second later the copy arrives, the lock is free, and it runs too. 23 runs, 1 skipped. A lock only stops copies that overlap, and a short job has finished before its copy arrives.
Let the lease run out
@celery_app.task(name="sweep_once")
def sweep_once():
worker = socket.gethostname()
got = r.set("lock:sweep", worker, nx=True, ex=LEASE)
if not got:
store.log_job("sweep", worker, "skipped")
return "skipped"
store.log_job("sweep", worker, "ran")
return run_sweep() # no release: the lease runs out
r.set with nx=True means set it only if nobody has: first one in wins. The second copy doesn't get it, so it's skipped. And it's never released; the lease runs out by itself, so keep it a little shorter than the gap (8 seconds with a sweep every 10 here; 240 against 300 by default). Twelve sweeps ran, twelve skipped, one notice. But the grep still showed Beat sending 12 plus 12. It stops double work, not double sends. The real fix is still one Beat.
Common mistakes
- A second Beat "for safety", or
-Bon every worker. - Crontab times read as local time.
- A stuck threshold shorter than the hard limit, failing healthy jobs.
- Releasing a once-per-slot lock in
finally. - No volume for the schedule file.
Quick recap
- Beat only sends tickets; workers do the work.
- Interval for a gap, crontab for a time on the clock (UTC by default).
- Keep stuck after longer than the hard limit.
- Run exactly one Beat, and add a lease so an accidental copy does no harm.
Try it yourself
Start the two-beats profile with sweep_released, count the runs, then switch to sweep_once and count again.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
