Skip to content

Lesson 39 of 59Product features

Scheduled Jobs and Cron Done Right

Run scheduled work in a Python service without duplicates or silent misses: where schedules live, locks, cron syntax, time zones, resumable jobs and monitoring.

21 min read0/5 questions

Every backend grows scheduled work: send the nightly invoices, expire stale carts every 15 minutes, email each user a reminder at 9am their time, rebuild a search index on Sundays. The first version is often a scheduler started inside the FastAPI app, and it works perfectly on a laptop. Then production runs four Uvicorn workers on three replicas, and every customer receives twelve invoices. The opposite failure is quieter and worse: the job stops running after a deploy and nobody notices for three weeks. This lesson is about running scheduled jobs exactly where you mean to, once, at the right time, and knowing when they did not.

Where a schedule can live

There are two separate pieces in every scheduled job: the trigger (something that knows the time and says "now") and the work (the code that runs). Most of the choices below are about where the trigger lives.

  • System cron on one VM. Simple and battle-tested, but it is tied to one machine: if that box dies, nothing runs, and if you clone the box, everything runs twice. Logs and failures go wherever you remember to send them.
  • Kubernetes CronJob. The cluster creates a short-lived Job (a pod running your image with a different command) on a schedule. It has the settings you want built in, shown below.
  • Cloud schedulers. Amazon EventBridge Scheduler and Google Cloud Scheduler fire on a cron expression, with time zones and retries, and call a target: a queue, a function, a container task, or an HTTPS endpoint on your service. If they call an endpoint, protect it like any internal API (Cloud Scheduler can attach an OIDC token you verify) and return quickly, handing the work to a queue.
  • Celery beat. If you already run Celery, as in Task Queues with Celery, beat is a single scheduler process that enqueues tasks, and your workers do the work with retries.
  • APScheduler in your own process. A Python library (the stable line is 3.x; 4.0 has been in pre-release for a long time, so check its status) with cron, interval and date triggers. Fine in a dedicated process. Dangerous inside your web workers, as the next section shows.
  • GitHub Actions schedule. Fine for low-stakes chores such as a weekly dependency report. Runs can start late under load, the shortest interval is five minutes, and in public repositories scheduled workflows are disabled after a period with no activity. Never use it for anything a customer would notice missing.
Match the pairs0/4 matched

Match each job to a sensible place for its trigger.

Choose an item, then its match on the other side.

A CronJob shows the settings that matter on any platform:

k8s/nightly-export.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-export
spec:
  schedule: "30 2 * * *"
  timeZone: "Etc/UTC"
  concurrencyPolicy: Forbid          # skip a run if the previous one is still going
  startingDeadlineSeconds: 600       # if it could not start within 10 minutes, skip it
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5
  jobTemplate:
    spec:
      backoffLimit: 2                # retry a failed pod twice
      activeDeadlineSeconds: 3600    # kill it after an hour
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: export
              image: registry.example.com/shop-api:2026.10.22
              command: ["python", "-m", "app.jobs.nightly_export"]

concurrencyPolicy: Forbid stops overlap, startingDeadlineSeconds stops a stale run firing hours late, and activeDeadlineSeconds stops a hung job holding resources forever. Even so, the Kubernetes docs say a CronJob can occasionally create two Jobs, or none, for one schedule, so the job itself must still be safe to run twice. That theme repeats through this lesson.

The in-process trap

Here is the version that ships by accident: start APScheduler in the FastAPI lifespan.

One scheduler per process means one run per process
Load balancerLoad balancerPod 1: 4 Uvicorn workersPod 14 Uvicorn workersPod 2: 4 Uvicorn workersPod 24 Uvicorn workersPod 3: 4 Uvicorn workersPod 34 Uvicorn workersEmail provider: invoicesEmail providerinvoicesScheduler: one processSchedulerone processx4x4x4x1

lifespan runs once per worker process, not once per app. With --workers 4, one pod starts four schedulers.

1/4
Predict the outputPython

An app starts an in-process scheduler in lifespan. It is deployed with uvicorn --workers 2 on 5 replicas, and autoscaling adds 1 replica at 02:00. How many times does the 02:00 job run?

workers_per_replica = 2
replicas = 5 + 1
print(workers_per_replica * replicas)
Need a nudge? Hints walk you through it.

There are two fixes, and serious teams often use both.

A dedicated scheduler process. Same image, different entrypoint, exactly one replica. With APScheduler it looks like this, and it runs outside Uvicorn entirely:

app/jobs/scheduler.py
import asyncio
 
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
 
from app.jobs.carts import expire_carts
 
 
async def main() -> None:
    scheduler = AsyncIOScheduler(timezone="UTC")
    scheduler.add_job(
        expire_carts,
        CronTrigger.from_crontab("*/15 * * * *", timezone="UTC"),
        id="expire-carts",
        replace_existing=True,
        max_instances=1,          # never overlap with itself
        coalesce=True,            # after downtime, run once, not once per missed slot
        misfire_grace_time=300,   # still run if we are up to 5 minutes late
    )
    scheduler.start()
    await asyncio.Event().wait()  # run until the container is stopped
 
 
if __name__ == "__main__":
    asyncio.run(main())

"Exactly one replica" is weaker than it sounds: during a rolling deploy the old and new pod can overlap for a few seconds, which is enough to double-fire a job scheduled at that moment.

A distributed lock around the work. Each run first tries to take a lock, and only the winner proceeds. In Redis that is one atomic command, SET key token NX PX ttl: set only if absent, with an expiry so a crashed holder cannot block the job forever.

Python
# 4 Uvicorn workers x 3 replicas, each running an in-app scheduler.PROCESSES = [f"pod{p}-w{w}" for p in range(1, 4) for w in range(1, 5)] class FakeRedis: """Just enough of SET key value NX PX ttl to show the idea.""" def __init__(self): self.data = {} # key -> (value, expires_at_ms) def set_nx_px(self, key, value, px, now_ms): held = self.data.get(key) if held and held[1] > now_ms: # someone holds it and it has not expired return False self.data[key] = (value, now_ms + px) return True def fire(now_ms, procs, redis=None, ttl_ms=60_000): """Every process's scheduler fires; returns who actually runs the job.""" ran = [] for proc in procs: if redis is None or redis.set_nx_px("lock:nightly-report", proc, ttl_ms, now_ms): ran.append(proc) return ran print("no lock: ", len(fire(0, PROCESSES)), "runs") r = FakeRedis()print("with SET NX PX:", fire(0, PROCESSES, r)) # The job takes 90 s but the lock only lives 60 s. At 61 s a scheduler# in another pod catches up on a misfire and tries again.r = FakeRedis()first = fire(0, PROCESSES, r)late = fire(61_000, PROCESSES[4:], r)print(f"at 61 s, {late} starts while {first} is still running")
Output
Press Run (⌘ Enter) to see what happens.

The last line is the classic lock bug. The expiry that protects you from a crashed holder also frees the lock under a holder that is merely slow.

A lock that expires mid-job
Pod 1RedisPod 2SET lock tok-A NX PX 60000OKSET lock tok-B NX PX 60000OKDEL lockdelete only if value is tok-A

Pod 1 wins the lock with a random token and starts the 90-second job.

1/6

In Python, redis.Redis.lock("lock:nightly-report", timeout=600, blocking=False) gives you a lock object with token checks and an extend() method, so you do not hand-write the script. If two runs overlapping would corrupt data rather than just waste work, a lock with an expiry is not enough on its own; you need fencing tokens, covered in Consensus and Leader Election, or a database constraint that makes the second run harmless.

If the job already talks to Postgres, an advisory lock avoids adding Redis:

app/jobs/locks.py
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession
 
 
async def try_job_lock(session: AsyncSession, job: str) -> bool:
    # Transaction-scoped: released automatically on commit, rollback or disconnect.
    result = await session.execute(
        text("SELECT pg_try_advisory_xact_lock(hashtext(:job))"), {"job": job}
    )
    return bool(result.scalar_one())
Advisory locks and connection pools

Postgres has two flavours. pg_try_advisory_lock is held by the session (the connection) until you unlock it or the connection closes. With a pool, the connection goes back to the pool still holding the lock, and an unlock sent on a different pooled connection does nothing. Behind PgBouncer in transaction mode it is worse, because consecutive statements may not even share a server connection.

pg_try_advisory_xact_lock is held until the transaction ends, so it cannot leak. The cost is a transaction open for the whole job, which blocks vacuum from cleaning up rows changed meanwhile. For a short job that is fine. For a long one, take the lock in a separate small connection that lives for the job, or use a lock table row with a locked_until column. Locks, Deadlocks and Safe Concurrency covers advisory locks in more depth.

Reading cron expressions

Five fields: minute, hour, day of month, month, day of week (0 or 7 is Sunday). * means every value, a-b a range, a,b a list, */n every nth value. So */15 9-17 * * 1-5 means every 15 minutes, from 09:00 through 17:45, Monday to Friday. Note that the hour range includes 17, so the last run is 17:45, not 17:00. That surprises people every time.

The second trap: when both day of month and day of week are restricted, classic cron runs if either matches, not both. 0 9 13 * 5 is "9am on the 13th and on every Friday", not "Friday the 13th". The parser below implements that rule.

Python
from datetime import datetime, timedelta def parse_field(text, low, high): """One cron field ('*', '*/15', '9-17', '1,3,5') -> set of ints.""" values = set() for part in text.split(","): rng, _, step = part.partition("/") if rng == "*": start, end = low, high elif "-" in rng: start, end = map(int, rng.split("-")) else: start = end = int(rng) values.update(range(start, end + 1, int(step or 1))) return values def next_runs(expr, after, count): minute, hour, dom, month, dow = expr.split() minutes, hours = parse_field(minute, 0, 59), parse_field(hour, 0, 23) days, months = parse_field(dom, 1, 31), parse_field(month, 1, 12) weekdays = {d % 7 for d in parse_field(dow, 0, 7)} # 0 and 7 are Sunday t = after.replace(second=0, microsecond=0) + timedelta(minutes=1) found = [] while len(found) < count: cron_dow = (t.weekday() + 1) % 7 # Python Monday=0, cron Sunday=0 if dom != "*" and dow != "*": # cron quirk: either day field may match day_ok = t.day in days or cron_dow in weekdays else: day_ok = t.day in days and cron_dow in weekdays if t.minute in minutes and t.hour in hours and t.month in months and day_ok: found.append(t) t += timedelta(minutes=1) return found friday_afternoon = datetime(2026, 10, 23, 17, 20) # a Friday, UTCfor run in next_runs("*/15 9-17 * * 1-5", friday_afternoon, 4): print(run.strftime("%a %H:%M")) print([r.strftime("%a %d") for r in next_runs("0 9 13 * 5", datetime(2026, 12, 1), 4)])
Output
Press Run (⌘ Enter) to see what happens.

Real schedulers jump straight to the next match instead of scanning minute by minute, and most add extensions (seconds fields, L for last day, names like MON). Those extensions differ between cron, Kubernetes, AWS and Quartz-style syntax, so check the docs of the scheduler you are writing for.

Quick check
Which runs does 0 6 1 * 1 produce?
Need a nudge? A hint rules out a wrong answer.

Time zones and daylight saving time

Schedule system jobs in UTC. Local time has hours that do not exist and hours that happen twice. In New York on 8 March 2026 the clocks jump from 02:00 to 03:00, so a job at 02:30 local has no moment to run at. On 1 November they fall back from 02:00 to 01:00, so 01:30 happens twice. Whether a local-time cron fires zero, one or two times then depends on the implementation, which is not something you want to discover from a customer.

User-facing schedules are different: "remind me at 9am" means 9am where the user is, all year. Store the wall-clock time and an IANA zone name (Europe/London, not +01:00, because the offset changes twice a year), and compute each next run with zoneinfo:

app/reminders/timing.py
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
 
 
def next_local_run(hour: int, minute: int, tz: ZoneInfo, after_utc: datetime) -> datetime:
    """Next hour:minute wall-clock time in tz, returned in UTC."""
    local = after_utc.astimezone(tz)
    candidate = local.replace(hour=hour, minute=minute, second=0, microsecond=0)
    if candidate <= local:
        candidate = (candidate + timedelta(days=1)).replace(hour=hour, minute=minute)
    return candidate.astimezone(timezone.utc)
 
 
london = ZoneInfo("Europe/London")
next_local_run(9, 0, london, datetime(2026, 10, 23, 12, 0, tzinfo=timezone.utc))
# 2026-10-24 08:00:00+00:00   (09:00 BST)
next_local_run(9, 0, london, datetime(2026, 10, 24, 12, 0, tzinfo=timezone.utc))
# 2026-10-25 09:00:00+00:00   (09:00 GMT, the clocks went back overnight)

The UTC time moves by an hour across the change, and the user still gets their reminder at 9am. Adding timedelta(days=1) to an aware datetime in Python keeps the wall-clock time, which is what you want here. For times that fall in a gap or overlap, Python's fold attribute picks which of the two readings you mean; for a 9am reminder you will never hit one, but a 01:30 reminder in New York would.

Quick check
Why store a user's schedule as 09:00 plus America/Chicago rather than as 15:00 UTC?
Need a nudge? A hint rules out a wrong answer.

Schedules that do not drift

If you write your own loop, the obvious version, run the job then sleep 60 seconds, drifts. Each run starts later by however long the job took.

Python
work_seconds = [3, 12, 1, 7, 30] # how long each run took clock = 0naive = []for w in work_seconds: naive.append(clock) clock += w + 60 # job time, then sleep 60 clock = 0scheduled = []for i, w in enumerate(work_seconds): slot = i * 60 clock = max(clock, slot) # wait for the slot scheduled.append(clock) clock += w print("sleep(60) loop starts:", naive)print("next-slot loop starts:", scheduled)
Output
Press Run (⌘ Enter) to see what happens.

The fix is to compute the next slot from the schedule, then sleep until it, as real schedulers do. If a run is still going when its next slot arrives, you must choose: skip it, run late, or run in parallel. That is exactly what max_instances, coalesce and Kubernetes concurrencyPolicy configure. Choose on purpose; the defaults are not the same everywhere.

Jobs that survive crashes and downtime

Scheduled jobs get killed by deploys, node drains and out-of-memory errors. Design every job so that running it again is the recovery plan.

  • Idempotent writes. A rerun must not double anything: upserts, unique constraints, or a "sent" marker per row, as in the idempotency section of Task Queues with Celery.
  • Batches with a checkpoint. Process a few hundred rows per transaction and record progress (a watermark: the last id or timestamp done) in the same transaction as the work. A crash loses at most one batch, and the rerun continues from the watermark.
  • Catch-up after downtime. If the scheduler was down for three hours, an every-15-minutes job has 12 missed slots. Usually you want one run that processes everything since the watermark, which is what coalesce=True gives you. A job built on a watermark catches up by itself, whereas a job that does "today's work" based on the clock silently skips the days it missed.
Python
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE events (id INTEGER PRIMARY KEY, user_id INT, amount INT);CREATE TABLE daily_totals (user_id INT PRIMARY KEY, total INT NOT NULL);CREATE TABLE job_state (job TEXT PRIMARY KEY, last_id INT NOT NULL);INSERT INTO job_state VALUES ('rollup', 0);""")db.executemany("INSERT INTO events (user_id, amount) VALUES (?, ?)", [(n % 3, 10) for n in range(1, 11)]) # 10 events, users 0-2db.commit() def run_rollup(batch_size=4, crash_after_batches=None): batches = 0 while True: (last_id,) = db.execute("SELECT last_id FROM job_state WHERE job='rollup'").fetchone() rows = db.execute( "SELECT id, user_id, amount FROM events WHERE id > ? ORDER BY id LIMIT ?", (last_id, batch_size)).fetchall() if not rows: return with db: # one transaction per batch for _id, user_id, amount in rows: db.execute("""INSERT INTO daily_totals VALUES (?, ?) ON CONFLICT(user_id) DO UPDATE SET total = total + excluded.total""", (user_id, amount)) db.execute("UPDATE job_state SET last_id=? WHERE job='rollup'", (rows[-1][0],)) batches += 1 print(f" batch done, watermark now {rows[-1][0]}") if batches == crash_after_batches: raise RuntimeError("pod killed") print("first run:")try: run_rollup(crash_after_batches=2)except RuntimeError as err: print(" crashed:", err) print("second run resumes:")run_rollup()print("third run, nothing new:")run_rollup() print(db.execute("SELECT user_id, total FROM daily_totals ORDER BY user_id").fetchall())print("expected total:", db.execute("SELECT SUM(amount) FROM events").fetchone()[0])
Output
Press Run (⌘ Enter) to see what happens.

The totals add up even though the job died halfway, because the increments and the watermark commit together. Move the watermark update outside the with db: block and a crash between the two would count a batch twice on the rerun. Use an increasing id as the watermark where you can; timestamps written by concurrent transactions can commit out of order and be skipped.

Per-user schedules: due dates, not cron entries

"Email each user at 9am local" is not a cron problem. A million users would mean a million cron entries. Instead, store a next_due_at timestamp (UTC) on each row, and run one poller every minute that claims due rows with FOR UPDATE SKIP LOCKED, the queue pattern from Locks, Deadlocks and Safe Concurrency:

claim_due_reminders.sql
UPDATE reminders
SET status = 'sending', claimed_at = now()
WHERE id IN (
    SELECT id FROM reminders
    WHERE status = 'scheduled' AND next_due_at <= now()
    ORDER BY next_due_at
    LIMIT 200
    FOR UPDATE SKIP LOCKED
)
RETURNING id, user_id, local_time, tz;

Several pollers can run this at once without claiming the same row, so this part scales and survives the double-scheduler problem by design. After sending, set next_due_at to the next local 9am using the function above and status back to scheduled. A separate sweep resets rows stuck in sending for too long, because a worker that died after claiming will never finish them. Index (status, next_due_at) so the claim stays fast.

Knowing that it ran

A failing request shows up in error rates. A job that never starts produces no errors at all. That is why scheduled jobs need dead man's switch monitoring: the job checks in when it finishes, and the monitor alerts when a check-in is missing.

Healthchecks.io works this way with a plain HTTP ping (https://hc-ping.com/<uuid>, plus /start and /fail variants, so it can also measure duration). Sentry Cron Monitors do the same from the Sentry SDK:

app/jobs/nightly_export.py
from sentry_sdk.crons import monitor
 
 
@monitor(monitor_slug="nightly-export")
def run() -> None:
    export_orders_since_watermark()

The decorator reports start, success or failure, and Sentry alerts if the check-in does not arrive in the expected window; the schedule and tolerance are set in Sentry or through monitor_config. Whatever tool you use, also emit metrics: run duration, rows processed, and a "last success" timestamp per job. Alert on "last success older than twice the interval", and on duration creeping up, since a 20-minute job that grows to 70 minutes will start overlapping an hourly schedule.

Put it in order5 steps

Put one run of a well-built nightly job in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
cron expression
Five fields (minute, hour, day of month, month, day of week) describing when a job fires.
misfire
A scheduled run that could not start on time, for example because the scheduler was down. Coalescing runs it once instead of once per missed slot.
distributed lock
A lock in a shared store such as Redis or Postgres so only one process across the fleet runs a job at a time.
advisory lock
A Postgres lock on an arbitrary number, held by a session or a transaction, used to coordinate application work.
watermark
The last id or timestamp a job has processed, stored so the next run continues from there.
IANA time zone
A named zone such as Europe/London that encodes the full history of offset and DST rules.
dead man's switch
Monitoring that alerts when an expected check-in does not arrive, catching jobs that silently stop running.