Skip to content

Scheduled jobs, cron and workers: running once across replicas, time zones, durable workflows and alerts

From crontab to durable workflows: why the job runs three times with three replicas, how to run it once with a lock, what Kubernetes CronJob promises and how to know the job ran.

Ramon Gomes 15 min read Level: Intermediate

Also available in: Español, Français, Português

Every real system has work nobody requests through the UI. Emailing the daily summary, generating the monthly bill, deleting temp files, syncing with a partner, reprocessing what failed. This work usually starts life as one line in the crontab, and it works fine until the day the system gets a second replica.

This article goes from cron to durable workflows: how each option works, the classic problems (the job that runs twice, the one that doesn't run, the one that runs at the wrong time) and how to know it actually ran. I checked everything against the official docs on November 21, 2026.

If you read the article on queues, a lot of this will sound familiar: a scheduled job is almost always just a message someone publishes at a set time.

Close-up of an old analog alarm clock on a wooden nightstand, hands near three in the morning, in the dim light of a lamp
The alarm rings on time. If your phone was off, it won't tell you that you missed it.

The Vocabulary

Term What it is
Job (or task) A unit of work: "generate the invoice for customer 42"
Scheduler What decides when a job should run
Worker The process that executes jobs, usually pulling them from a queue
Cron The classic Unix scheduler, and also the name of the five-field syntax
Durable workflow A multi-step process that survives failures and restarts by saving where it stopped

The most useful split: scheduling and executing are different things. A good scheduler only publishes "it's time", and the workers do the work. That way you scale workers without multiplying the schedule.

Cron in Five Fields

text
┌───────── minute (0 to 59)
│ ┌─────── hour (0 to 23)
│ │ ┌───── day of month (1 to 31)
│ │ │ ┌─── month (1 to 12)
│ │ │ │ ┌─ day of week (0 to 7, Sunday is 0 or 7)
│ │ │ │ │
30 3 * * 1-5   /usr/local/bin/backup.sh

This example runs at 3:30 AM, Monday through Friday. There are shortcuts like @daily (midnight) and @hourly. Tools like crontab.guru turn the expression into plain English and save you a lot of mistakes.

Two gotchas documented in the crontab manual:

  • Day of month and day of week together become "OR". 30 4 1,15 * 5 doesn't run "on the 1st and 15th when they fall on a Friday". It runs on the 1st and 15th and every Friday.
  • % becomes a newline. date +%F inside the crontab breaks the command. You have to write \%.

Cron's Three Problems in Production

1. With Several Replicas, the Job Runs Several Times

If the schedule lives inside the application (a node-cron, a @Scheduled) and you run three replicas to handle traffic, at 3 AM all three wake up and do the same work. The customer gets three emails. The bill is generated three times.

Two panels at 03:00: without a lock, three replicas send three copies of the same email to the customer; with a lock, one replica sends one email and the other two skip the run.
Three replicas, three runs. With a lock, only whoever grabs the key does the work.

2. If the Machine Is Off, the Job Doesn't Run

Cron checks the clock every minute. If the machine was off at 2 AM, the 2 AM job simply doesn't happen, and nobody is told. Linux has two answers for this: anacron, which records the last day each job ran and runs the overdue one when the machine boots, and systemd timers with Persistent=true, which do the same for any time of day.

Shared timeline: the server is off from midnight to 8 AM. Below, two panels with clocks at 2 AM: cron misses the job and nothing runs at 8; the systemd timer with Persistent=true retains the pending job and runs it at 8:01.
Cron just skips it. The persistent timer remembers and runs it at boot.

3. When It Fails, Nobody Finds Out

Cron emails the output to the crontab owner, if there's a mail server configured (there almost never is). In practice, a job can fail every day for months in silence. We'll come back to this at the end of the article.

Daylight Saving Time and Time Zones

If you have users or servers in countries with daylight saving time, two hours a year mess up scheduling:

  • When the clock springs forward, a time stops existing. The 2:30 AM job may not run.
  • When the clock falls back, a time happens twice. The 2:30 AM job may run twice.
Two panels with clock times and hour sequences: when daylight saving time starts, 01:59 jumps to 03:00 and the 2:30 job does not run; when it ends, 02:59 returns to 02:00, the hour repeats and the job runs twice.
One hour that doesn't exist and one hour that happens twice.

And every tool handles it differently. EventBridge Scheduler skips the run when clocks spring forward and runs only once when they fall back. Trigger.dev adjusts on its own when the time zone is set. Inngest warns in its docs that it doesn't correct for daylight saving and may run 0, 1 or 2 times on the day of the change. Linux cron itself has a compensation for changes under 3 hours, but the crontab and daemon manuals describe the case in ways that seem to conflict.

The rule of thumb: schedule in UTC or outside the changeover window, and leave the time zone conversion for when you display the result.

A Kubernetes-specific trap: putting CRON_TZ=America/Sao_Paulo inside the CronJob schedule was never supported and now fails validation. The right way is the .spec.timeZone field, stable since version 1.27.

Running Only Once Across Several Replicas

Option 1: A Lock in Redis

Before running, each replica tries to create a key that can only exist once:

text
SET job:daily-report <random-value> NX PX 600000

NX only creates it if it doesn't exist; PX makes the key expire in 10 minutes, so it doesn't stay locked forever if the process dies. Whoever created it runs. The others give up.

To release it, the Redis docs ask for one precaution: delete the key only if it's still yours, by comparing the random value (with a Lua script or, from Redis 8.4 on, with DELEX ... IFEQ). A plain DEL can delete a lock that has already passed to another replica.

The Distributed Lock Debate

In 2016, Martin Kleppmann published a critique everyone who uses locks should read. The core point: a process can pause (a long garbage collection, a network delay) while holding the lock. The lock expires, another process grabs it, and the first one wakes up thinking it's still the owner.

Three cards with flows: A freezes in a GC pause, the lock expires and B acquires it; without a control number, A overwrites B; with a fencing token, the database keeps B’s value and token 34, rejecting A’s token 33.
Without a control number, the old owner doesn't know it's no longer the owner.

His conclusion splits two cases, and it's worth its weight in gold:

  • Lock for efficiency (running twice only wastes resources or sends one extra email): a simple Redis lock is enough.
  • Lock for correctness (running twice corrupts data or charges twice): a lock with a timeout isn't enough. You need a fencing token (an increasing number the database uses to reject stale writes) or, even better, an idempotent job.

Option 2: Postgres Advisory Lock

If you already have Postgres, you don't need Redis for this:

sql
SELECT pg_try_advisory_xact_lock(4242);  -- true: you run; false: someone else is already running

The xact version is scoped to the transaction and released on its own at COMMIT or ROLLBACK. The session version (pg_try_advisory_lock) is tied to the connection, which is risky with a connection pool in transaction mode, because the lock can end up on the wrong connection.

Option 3: A Scheduler That Already Handles It

Several tools already take care of this, and it's the path I recommend:

Tool Stack How it guarantees one run
pg-boss 12.39 Node + Postgres Checks schedules every 30 s and sends only one job, even with several instances
BullMQ 6.7 (Job Schedulers) Node + Redis Special IDs prevent creating the job more times than configured
Quartz 2.5 clustered Java + database The first node to lock the trigger in the database fires it; clocks must be in sync
Celery beat 5.7 Python Requires a single beat process; two beats create duplicate tasks
Sidekiq Enterprise Ruby Elects a leader that creates the jobs (paid feature)
Hangfire 1.8 .NET Recurring jobs stored in the database
ts
// pg-boss: schedule once, run on any worker
await boss.schedule('daily-report', '0 6 * * *', null, { tz: 'America/Sao_Paulo' });
await boss.work('daily-report', async () => generateReport());

Option 4: A Managed Scheduler

If you're in the cloud, the scheduler can live outside your app and call an endpoint or publish to a queue:

  • AWS EventBridge Scheduler: rate(), cron() and at() (one-time) expressions, configurable time zone, 60-second precision, more than 270 services as targets.
  • Google Cloud Scheduler: calls HTTP, Pub/Sub or App Engine. It sends the X-CloudScheduler-JobName and X-CloudScheduler-ScheduleTime headers, which you can use to deduplicate.
  • Vercel Cron Jobs: 100 per project. On the Hobby plan, at most once a day and up to 59 minutes off.
  • GitHub Actions schedule: 5-minute minimum interval, delays at peak times (the top of every hour) and is turned off automatically in a public repo with no activity for 60 days.

Note that the first two document at-least-once delivery. Again: the job has to handle running twice.

Kubernetes CronJob

A Kubernetes CronJob creates a Job at each scheduled time. Three fields deserve attention:

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: daily-report
spec:
  schedule: "0 6 * * *"
  timeZone: "America/Sao_Paulo"
  concurrencyPolicy: Forbid        # don't start another if the previous one is still running
  startingDeadlineSeconds: 600     # if it's more than 10 min late, skip it
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: report
              image: my-app:1.4.2
              command: ["node", "dist/jobs/report.js"]
          restartPolicy: OnFailure

And the warning in the official docs, which applies to any scheduler: a CronJob creates a job approximately once per scheduled time, because there are circumstances where it may create two, or none. "Therefore, jobs should be idempotent."

Workers: Stopping Without Breaking Anything

A worker is a process that loops pulling work. The most delicate moment is shutdown. On Kubernetes, the process gets SIGTERM and has 30 seconds (default) before it's force-killed.

Animation of a worker processing a job when the SIGTERM signal arrives; in the correct version, it stops taking new jobs, finishes the current one within the 30 seconds and exits; in the wrong version, it's killed halfway and the job is stuck until another worker picks it back up
On SIGTERM: take nothing new, finish what's in hand, exit.
ts
const worker = new Worker('reports', processJob, { connection });

process.on('SIGTERM', async () => {
  await worker.close(); // stops taking jobs and waits for active ones to finish
  process.exit(0);
});

If the process still dies halfway, BullMQ detects the stalled job and another worker picks it back up. One more reason for the job to be idempotent: it may have done half the work the first time.

When the Problem Is Bigger Than a Job: Durable Workflows

Some processes have several steps and last hours or days: "charge, wait 3 days for payment, send a reminder, cancel if unpaid". Building this with cron and state tables is possible, but fragile.

That's what durable workflow orchestrators are for. Temporal (server 1.32) is the best known: the workflow code looks like ordinary code, with await sleep('3 days') in the middle, and Temporal guarantees it picks up where it left off, even if every server restarts. The price: workflow code has to be deterministic, because it's replayed from history when it resumes.

Lighter alternatives, popular in serverless projects: Inngest and Trigger.dev, which keep the schedule and the state outside your app. And for data pipelines with a start and an end, Apache Airflow (version 3.4) is still the reference.

Situation Tool that's usually enough
One server, simple task cron or systemd timer
Several replicas, already on Postgres pg-boss
Several replicas, already on Redis and Node BullMQ
In the cloud, nothing to manage EventBridge Scheduler, Cloud Scheduler
Multi-step process that lasts days Temporal, Inngest, Trigger.dev
Data pipeline Airflow

How to Know the Job Ran

Monitoring errors isn't enough, because a job that didn't run doesn't raise any error. The right technique is the dead man's switch: the job pings an external service every time it finishes, and the alarm goes off when the ping doesn't arrive.

Nightly backup server, four run signals and a heart with OK status; below, a signal-over-time chart with a gap, late status after the grace period and down status. Beside it, a phone at 03:14 alerts that the nightly backup is down.
The alert isn't the job checking in. It's the job going quiet.
sh
# at the end of the script, only if it succeeded
/usr/local/bin/backup.sh && curl -fsS -m 10 --retry 3 https://hc-ping.com/<your-uuid>

In Healthchecks.io, you set the period (1 hour) and a grace time (5 minutes). If the last ping was at 12:00 PM, at 1:00 PM the job is marked "late" and at 1:05 PM "down". You can also send a start ping, to catch the job that started and hung. Cronitor and Sentry Crons do the same, and Healthchecks can be self-hosted.

Together with the job's own logs and metrics, this rounds out observability for background work.

Cartoon of three identical building doormen calling the building manager at the same time at eight in the morning, each with a phone in hand, while the manager desperately answers three identical calls
Three replicas, the same task list and no agreement between them.

Quick check

1. Your API runs on 3 replicas, each with node-cron scheduling the same email at 7 AM. How many emails does the customer get?
Show answer

Answer: 3, one per replica

A schedule inside the app runs in every process. You need a lock or a single scheduler.

2. What do the Kubernetes docs say about CronJob?
Show answer

Answer: That it may create two jobs or none, so jobs should be idempotent

That's why idempotency comes up with every scheduler.

3. What is a dead man's switch in job monitoring?
Show answer

Answer: An alert fired when the job stops sending a sign of life

It catches the job that never even ran, which no error alert sees.

Frequently Asked Questions

Is cron still useful?

Very much so on a single machine, for maintenance tasks. In an app with replicas, prefer a scheduler that guarantees a single run.

Do I need a queue to have scheduled jobs?

Not necessarily, but it helps. With a queue, the scheduler only publishes and any worker executes, and you get retries and failure records for free.

What's the difference between a scheduled job and a workflow?

A job is a unit of work triggered by time. A workflow is a sequence of steps with state, which can last days and has to pick up where it left off.

How do I test a scheduled job?

Separate the logic from the schedule: the generateReport() function is tested like any other, without waiting for the clock. The article on back-end testing shows how.

What about serverless?

It works well with a managed scheduler (EventBridge, Vercel Cron, Cloud Scheduler), because there's no process running all the time to keep the clock.

References

Checked on November 21, 2026:

Source: https://ramongomessilva.com.br/blog/scheduled-jobs-cron-and-workers · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. Scheduled jobs, cron and workers: running once across replicas, time zones, durable workflows and alerts. Ramon Gomes, 29 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/scheduled-jobs-cron-and-workers. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 29). Scheduled jobs, cron and workers: running once across replicas, time zones, durable workflows and alerts. Ramon Gomes. https://ramongomessilva.com.br/blog/scheduled-jobs-cron-and-workers

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026scheduledjobscron,
  author = {Gomes, Ramon},
  title = {{Scheduled jobs, cron and workers: running once across replicas, time zones, durable workflows and alerts}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-29},
  url = {https://ramongomessilva.com.br/blog/scheduled-jobs-cron-and-workers},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles