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.
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-livedJob(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 each job to a sensible place for its trigger.
A CronJob shows the settings that matter on any platform:
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.
lifespan runs once per worker process, not once per app. With --workers 4, one pod starts four schedulers.
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)
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:
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.
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.
Pod 1 wins the lock with a random token and starts the 90-second job.
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:
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.
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.
0 6 1 * 1 produce?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:
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.
09:00 plus America/Chicago rather than as 15:00 UTC?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.
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=Truegives 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.
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:
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:
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 one run of a well-built nightly job in order.
- Tap the steps below in the right order.
- 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.