You added cron.schedule("0 7 * * 1-5", sendDigest) to server.js, watched it fire locally, and shipped it. Then production happened. The digest went out four times because PM2 runs four instances. Or it never went out, because the container scaled to zero overnight. Or it went out on time, and every API request sat waiting for the 40 seconds it took to build.
Node has no built-in scheduler, so "Node.js cron job" really means picking who owns the clock: the operating system, a library inside your process, a job queue, your cloud platform, or an outside service that calls your code over HTTP. This guide covers each one with working code for Node 22, 24 and 26 (the LTS lines as of November 2026), and the traps that are specific to Node: the single event loop, cluster mode, and scripts that refuse to exit.
Decide who owns the clock before you pick a library
Most Node scheduling bugs come from putting the clock somewhere that doesn't match how the code runs. A timer inside a web server is fine on one VM and wrong on a platform that runs three copies of it, or none. So start with where your Node code lives today, then read the matching section.
| Who owns the clock | Extra process to keep up | Copies that fire | A run due during downtime | Timezone |
|---|---|---|---|---|
crontab + node script.js | No | One per server | Skipped | Server zone |
| node-cron, cron, croner, Bree | Your app, always on | One per process | Skipped | Per job |
| BullMQ, pg-boss, Agenda | Workers plus Redis or DB | One, by design | Kept or configurable | Per schedule |
| Vercel, Netlify, Cloudflare cron | No | One, best effort | Platform's call | Mostly UTC |
| HTTP route + Crontap | No, the app is up anyway | One call, any replica | Retried, then alerted | Per schedule |
The in-process row is the one most Node apps start with, because it's one npm install away. It's also the one that breaks first when the app grows to more than one process.
crontab: a Node script on one server, and why it fails quietly
If you have one Linux box and SSH, crontab is the shortest path. Open it with crontab -e and add a line. The five fields are covered in what is a cron job in Linux, and the cron syntax cheat sheet has the common patterns.
# m h dom mon dow command
CRON_TZ=America/New_York
0 7 * * 1-5 cd /opt/app && /usr/bin/flock -n /tmp/digest.lock /usr/local/bin/node --env-file=.env jobs/digest.js >> /var/log/digest.log 2>&1Every part of that line is there because something broke without it. Cron starts your command with /bin/sh, a tiny PATH, your home directory and none of your shell profile, and that hits Node in three specific ways.
- 1
Find node by its full path, not through nvm
nvm only loads in interactive shells, so
node: command not foundis the classic first failure even though Node is installed. Runwhich node(ornvm which 24) and paste that absolute path, or symlink one version to/usr/local/bin/node. Pin the version, so a laternvm alias defaultdoesn't quietly change what runs at 07:00. - 2
Load the environment yourself
Cron doesn't read your
.envfile. Since Node 20.6,node --env-file=.envloads it without thedotenvpackage; the path is relative to the working directory, which is why the line starts withcd.CRON_TZsets the schedule's zone on cronie; on crons that don't support it, the line runs in the server's timezone. - 3
Make sure the script actually exits
A script that opens a Postgres pool, a Redis client or a Prisma connection stays alive until those are closed. Cron then starts the next run next to a process that never ended, which is what
flock -nprotects you from. Close what you open, and report failure through the exit code:// jobs/digest.js import { pool } from "../lib/db.js"; import { sendDigest } from "../lib/digest.js"; try { await sendDigest(); } catch (err) { console.error(err); process.exitCode = 1; } finally { await pool.end(); // without this, the process never exits }
On systemd hosts, a timer unit does the same job with a timezone per timer and catch-up after downtime (Persistent=true). The Python cron guide walks through the unit files, and they work the same with ExecStart=/usr/local/bin/node. In containers, read the Docker cron jobs guide before you install cron in your image.
In-process schedulers: node-cron, cron, croner, node-schedule and Bree
These run inside a Node process that you keep alive: your web server, or a small worker next to it. They're the most natural fit for Node, since a schedule is a function call, and the trade-off is that the schedule only exists while that process does. Here is where each one stands, checked on npm in November 2026.
| Library | Version | Overlap option | A tick that fires late | Worth knowing |
|---|---|---|---|---|
node-cron | 4.6.0 | noOverlap | Dropped after 1 s, logged as missed | Events, distributed, file tasks in a fork |
cron | 4.4.0 | waitForCompletion | Dropped after threshold (250 ms) | CronJob.from(), Luxon timezones |
croner | 11.0.1 | protect | Not documented | No dependencies; Node, Deno, Bun, browser |
node-schedule | 2.1.2 | None | Not documented | Date and object rules; first release since 2023 |
bree | 9.2.9 | Built in, one at a time | Not documented | Every run is a worker thread |
All five take cron expressions and an IANA timezone. The tabs below schedule the same weekday 07:00 digest in New York time with each library, so you can compare them line by line.
Same digest, five libraries
import cron from "node-cron";
import { sendDigest } from "./jobs/digest.js";
cron.schedule("0 7 * * 1-5", sendDigest, {
name: "morning-digest",
timezone: "America/New_York",
noOverlap: true, // skip a tick while the last run is still going
});node-cron 4.6, Node 20+. It combines day-of-month and weekday with AND, where classic cron uses OR.
That's also why you shouldn't hand-roll this with setInterval. An interval drifts with every slow run and restarts from zero on every deploy, and setTimeout can't wait longer than 2,147,483,647 ms (about 24.8 days). Node's docs say a larger delay is set to 1 ms, so "run this in 30 days" fires almost immediately.
When a run outlives its minute: overlaps, skips and a blocked event loop
Here is the part that's different in Node. Your scheduler, your HTTP server and your job share one event loop. A job that awaits network calls leaves the loop free, so the scheduler keeps ticking and starts the next run on time, even if the last one hasn't finished. A job that burns CPU synchronously holds the loop, so nothing else runs: not the next tick, not your API.
Try it below. It's one Node process running a node-cron schedule every minute for eight minutes, following node-cron 4.6's rules. Drag the run past 60 seconds, then switch the job to CPU on the main thread.
Event loop simulator
cron.schedule("* * * * *", buildReport);
HTTP server, same processevent loop free
- Ran on time
- Ran on top of the last run
- Skipped: still running
- Missed: event loop blocked
- Runs started
- 8
- Most at once
- 2
- Skipped
- 0
- Missed
- 0
- API frozen
- 0s
Runs pile up: up to 2 copies at once, sharing one connection pool and racing on the same rows.
stdout, first lines
- 02:00:00run 1 starts
- 02:01:00run 2 starts while run 1 is still going
- 02:02:00run 3 starts while run 2 is still going
- 02:03:00run 4 starts while run 3 is still going
- 02:04:00run 5 starts while run 4 is still going
- 02:05:00run 6 starts while run 5 is still going
Three different failures come out of that one schedule:
- Overlap (I/O job, defaults). Each tick starts another run, so a 75-second job on a one-minute schedule always has two copies in flight, sharing one connection pool and racing on the same rows.
cronandcronerbehave the same until you setwaitForCompletionorprotect. - Skip (
noOverlap: true). One run at a time, which is usually what you want, but your "every minute" job now runs every two minutes. node-cron logs a warning and emitsexecution:overlapeach time. - Missed (CPU on the main thread). The timer can't fire while the loop is busy. When it finally does, node-cron sees it's more than
missedExecutionTolerance(1,000 ms by default) late, drops that run and logs a missed execution.crondoes the same past its 250 msthreshold. Meanwhile every request to the same process waits.
The fix for the first two is an option. The fix for the third is to get the work off the main thread: node-cron 4 runs a task in a forked process when you pass a file path instead of a function, Bree runs every job in a worker thread, and node:worker_threads lets you do it by hand. Then listen to node-cron's events, so skipped and missed runs show up in your logs and metrics instead of vanishing:
import cron from "node-cron";
const task = cron.schedule("* * * * *", "./tasks/report.js", {
name: "report",
noOverlap: true,
});
task.on("execution:overlap", () => metrics.increment("report.skipped"));
task.on("execution:missed", () => metrics.increment("report.missed"));
task.on("execution:failed", (ctx) => logger.error(ctx.execution?.error));If you bundle the app with esbuild or webpack, mark node-cron as external, or the forked file task can't find its helper script.
Job queues: when the schedule has to survive restarts and replicas
Once a missed or doubled run costs money, move the schedule into a queue. The queue keeps the schedule and the jobs in Redis or a database, any number of workers can process them, and a job that came due during a deploy is still there afterwards. The price is more to run: Redis or a database, plus workers that stay up.
Same digest, three queues
import { Queue, Worker } from "bullmq";
import { sendDigest } from "./jobs/digest.js";
const connection = { host: "127.0.0.1", port: 6379 };
const queue = new Queue("digest", { connection });
// Same id on every boot: updates the scheduler instead of adding one
await queue.upsertJobScheduler(
"morning-digest",
{ pattern: "0 7 * * 1-5", tz: "America/New_York" },
{ name: "send-digest" }
);
new Worker("digest", async () => sendDigest(), { connection });BullMQ 6.7 on Redis. The scheduler adds the next job only when the current one starts processing.
- BullMQ (6.7, Redis) calls them job schedulers.
upsertJobSchedulerwith the same id on every boot updates one scheduler instead of adding another, so every replica can call it. The scheduler keeps one delayed job at a time and only adds the next when the current one starts processing, so a backed-up queue runs less often than the pattern says. Older code uses therepeatoption onqueue.add; the job schedulers guide is the current API. - pg-boss (12.38, Postgres 13+) checks schedules every 30 seconds, so the finest cadence is one job a minute, and uses its own throttling so only one job is sent even when several instances call
schedule(). It runs in UTC unless you passtz, and itsmissedoption decides whether runs that came due during an outage are skipped (the default) or sent once. - Agenda (6.2, ESM only) now stores jobs in MongoDB, PostgreSQL or Redis through a backend package, and
every()creates one job in the database however many times the line runs. A lock with a 10-minute default lifetime keeps two Agenda instances from processing the same job.
If you already run Postgres, pg-boss adds no new infrastructure. If you already run Redis and need lots of workers, BullMQ. The Postgres cron guide covers scheduling inside the database itself with pg_cron.
PM2 cluster mode, replicas and the job that runs four times
Every in-process scheduler runs once per process. That's obvious when you write it and easy to forget when you scale: pm2 start server.js -i max on a four-core box, two Kubernetes replicas, or a Fly app in three regions all start their own copy of cron.schedule, and every copy fires. The digest goes out four times, and the billing job charges twice.
There are four ways out, from quickest to sturdiest:
-
Pick one process. PM2 gives each cluster process a unique
NODE_APP_INSTANCEnumber, and its docs suggest exactly this guard. The catch: if instance 0 is down or stuck, the job runs nowhere, and outside PM2 the variable doesn't exist.if (process.env.NODE_APP_INSTANCE === "0") { cron.schedule("0 7 * * 1-5", sendDigest, { timezone: "America/New_York" }); } -
Let node-cron coordinate. With
distributed: true, node-cron 4.6 readsNODE_CRON_RUN: set it totrueon one instance andfalseon the rest, and it throws at startup if it's missing. For failover, plug in@node-cron/redis-coordinator: every replica races for a Redis lock keyed on the task name and fire time, and the winner runs. Its docs say plainly that this isn't exactly-once, so the job still has to be safe to repeat. -
Use a queue. BullMQ's upsert and pg-boss's throttling are built for many instances, as described above.
-
Move the clock out of the app. An outside scheduler calls one URL and your load balancer hands it to one replica. Nothing in the app needs to know how many copies exist.
Serverless: Vercel, Netlify, Cloudflare and AWS
On serverless there's no long-running process to hold a timer, so the platform calls your function on its own clock. Each has its own limits, and we've written those up separately. Here is the short version, as of November 2026.
| Platform | Where the schedule lives | What to watch | Details |
|---|---|---|---|
| Vercel Cron Jobs | crons in vercel.json, a GET | UTC only; Hobby runs once a day, anywhere in the hour; no retries | Vercel cron limits |
| Netlify scheduled functions | export const config = { schedule } | UTC; 30-second limit; can't be called by URL; not on previews | Netlify alternative |
| Cloudflare Workers Cron Triggers | triggers.crons in Wrangler config | UTC; 5 per account on Free; changes take up to 15 minutes | Cloudflare limits |
| AWS EventBridge Scheduler | cron(0 7 ? * MON-FRI *) plus a zone | Six fields with ?; an IAM role for the target | Lambda without EventBridge |
Vercel's own docs say cron delivery is best effort and can occasionally deliver the same run twice, and that a job running longer than its interval can overlap the next one. So the next two sections apply to platform crons as much as to node-cron.
The HTTP trigger: an Express, Fastify or Next.js route on an outside clock
If your Node code already runs as a web app, the job doesn't need a scheduler of its own. Put it behind a route that only accepts a secret header, deploy it like any other endpoint, and let an external scheduler call that URL on a cron. Nothing extra stays running, any replica can answer, and the schedule lives somewhere you can see and change without a deploy.
One route, three frameworks
import express from "express";
import { isScheduler } from "./lib/cronAuth.js";
import { sendDigest } from "./jobs/digest.js";
const app = express();
app.post("/internal/morning-digest", async (req, res) => {
if (!isScheduler(req.get("authorization"))) return res.sendStatus(401);
await sendDigest(); // Express 5 turns a rejection into a 500
res.sendStatus(204);
});
app.listen(process.env.PORT ?? 3000);Express 5 forwards a rejected promise to the error handler, so a failed run answers 500. On Express 4, wrap the body in try/catch.
timingSafeEqual compares the header in constant time, so the secret can't be guessed from response timings, and the length check comes first because it throws on buffers of different lengths. The route runs the job inline on purpose: a crash becomes a 500, and a 500 is something a scheduler can retry and alert on.
- 1
Deploy the route with a CRON_SECRET
Generate a value with
node -p "require('node:crypto').randomBytes(32).toString('base64url')", set it asCRON_SECRETon the host, and deploy. Call the route once withcurl -X POST -H "Authorization: Bearer $CRON_SECRET" https://api.example.com/internal/morning-digestand check for a 204. - 2
Create the schedule
In Crontap, add a
POSTto that URL with theAuthorization: Bearer ...header, set the cron to0 7 * * 1-5and pickAmerica/New_Yorkfor this schedule. Runs follow that zone through daylight saving changes, so 07:00 stays 07:00. - 3
Press Perform test
Perform test calls the route right now and shows the status code, timing and response, so a wrong header or a missing env var shows up today instead of at 07:00 tomorrow.
- 4
Decide what failure means
New schedules retry 5xx responses, timeouts and network errors with exponential backoff and record every attempt. When the attempts run out, Crontap alerts you by email on every plan, or in Slack, Discord or Telegram on paid plans.
For jobs that outlast your host's request timeout, answer 202 right away and hand the work to BullMQ or pg-boss; the worker does the long part, and a heartbeat at the end tells you it finished. The honest trade-offs: the route has to be reachable over HTTPS, so it needs that secret check; Crontap calls your code rather than running it; and a run that takes longer than the interval can overlap the next call, so keep the lock from the next section. The free plan covers two schedules or monitors at intervals down to one hour; paid plans go down to every minute.
Make the job safe to run twice
Whichever clock you choose, plan for the run that happens twice: a deploy restarts a worker mid-run, a retry resends a request, a platform cron double-delivers, or someone runs the job by hand while the scheduled one is going. Two small guards cover most of it.
// Postgres (pg): one runner at a time, released when the transaction ends
const client = await pool.connect();
try {
await client.query("BEGIN");
const { rows } = await client.query(
"SELECT pg_try_advisory_xact_lock(hashtext('morning-digest')) AS ok"
);
if (rows[0].ok) await sendDigest(client);
await client.query("COMMIT");
} finally {
client.release();
}
// Redis (node-redis): a lock that expires on its own if the process dies
const got = await redis.set("lock:morning-digest", "1", {
NX: true,
PX: 600_000,
});
if (got) await sendDigest();Then make the work itself repeatable: record what you've sent before you send it, use upserts instead of inserts, and pass idempotency keys to payment APIs.
Know when a run didn't happen
Failures come in two kinds. A loud failure throws, returns a 500 or exits non-zero, and you can catch it. A quiet failure is a run that never started: the worker that crashed at 03:00, the node-cron tick that was missed, the crontab on a server someone rebuilt. Logs can't show you a run that didn't happen.
For the HTTP trigger, the schedule covers loud failures with retries and alerts. For everything else, have the job report in. A heartbeat is a URL your job calls when it finishes, and its /fail URL when it doesn't:
const HEARTBEAT = "https://ping.crontap.com/YOUR-TOKEN";
try {
await sendDigest();
await fetch(HEARTBEAT);
} catch (err) {
await fetch(`${HEARTBEAT}/fail`);
throw err;
}A /fail ping alerts right away, and silence alerts once the period plus grace has passed. If the job still won't fire and you can't see why, work through cron job not running.
FAQ
Node.js cron job questions
- How do I run a cron job in Node.js?
- Install node-cron (npm install node-cron) and call cron.schedule("0 7 * * 1-5", sendDigest, { timezone: "America/New_York" }) in a process that stays running. If the process restarts, scales to zero or runs as several copies, schedule outside it instead: crontab running a Node script on one server, a job queue such as BullMQ or pg-boss, your platform's cron, or an external scheduler calling an HTTP route.
- Should I use node-cron, cron or croner?
- All three take cron expressions with an optional seconds field, accept an IANA timezone and keep schedules in memory. node-cron 4.6 adds noOverlap, events and a distributed option; cron 4.4 has waitForCompletion and a late-tick threshold; croner 11 has no dependencies, runs in Node, Deno, Bun and browsers, and uses protect for overlap. Pick the one whose options you need. None of them remembers runs across a restart.
- Why does my Node cron job run several times in production?
- An in-process scheduler runs once per process. PM2 cluster mode with four instances, four Kubernetes replicas or two regions each start their own copy, and each copy fires the job. Run the schedule in one place: guard it with PM2's NODE_APP_INSTANCE, use node-cron's distributed option with a Redis coordinator, move the job into a queue, or call one HTTP route from an external scheduler.
- How do I run a node-cron job on only one PM2 instance?
- PM2 gives every cluster process a unique NODE_APP_INSTANCE number, so wrap the schedule in if (process.env.NODE_APP_INSTANCE === "0"). The catch: if instance 0 is down or stuck, the job runs nowhere, and the number means nothing outside PM2. For containers, node-cron's distributed option with a Redis coordinator lets whichever replica wins a lock run each tick.
- What happens when a Node cron job takes longer than its interval?
- By default node-cron, cron and croner start the next run anyway, so runs stack up and share the same connection pool and rows. Turn on noOverlap (node-cron), waitForCompletion (cron) or protect (croner) to skip ticks while a run is in progress. If the job is CPU-bound and synchronous, it also blocks the event loop, so ticks fire late and node-cron drops them as missed.
- Why does node-cron log "missed execution"?
- node-cron 4.6 logs "missed execution ... Possible blocking IO or high CPU" when its timer fires more than missedExecutionTolerance (1000 ms by default) after a scheduled time, and it skips that run instead of running it late. The usual cause is synchronous work blocking the event loop, often the cron job itself. Move heavy work to a worker thread or a child process, or listen for the execution:missed event to handle it.
- How do I set a timezone for a Node.js cron job?
- Pass an IANA zone: timezone in node-cron, croner, Bree and Agenda's every(), timeZone in the cron package, tz in node-schedule, BullMQ's upsertJobScheduler and pg-boss's schedule(). Without it, most libraries use the server's local zone, and pg-boss uses UTC. Vercel Cron Jobs, Netlify scheduled functions and Cloudflare Cron Triggers always run in UTC; Crontap stores a timezone per schedule.
- Should I use BullMQ, Agenda or pg-boss for scheduled jobs?
- Use the one that matches a database you already run. BullMQ needs Redis and gives you job schedulers, retries and many workers. pg-boss runs on Postgres, checks schedules every 30 seconds and makes sure only one job is sent even with several instances. Agenda 6 stores jobs in MongoDB, PostgreSQL or Redis through a backend package. All three survive restarts, unlike node-cron.
- Why does my Node script work by hand but not from crontab?
- Cron runs commands with /bin/sh and a minimal PATH, so node from nvm is not found, and your .env file is not loaded. Use the absolute path to the node binary (which node shows it), cd into the project, and pass --env-file=.env. Also make sure the script exits: an open database pool or Redis client keeps Node alive, and the next run piles on top.
- How do I run Node cron jobs on Vercel, Netlify or Cloudflare?
- Each platform calls your function on its own clock, mostly in UTC. As of November 2026 Vercel Cron Jobs (legacy) run once a day on Hobby (anywhere within the hour) and every minute on Pro, while the Vercel Schedules beta runs every 15 minutes on Hobby in any IANA timezone; Netlify scheduled functions have a 30-second limit; Cloudflare Workers use Cron Triggers in the Wrangler config and a scheduled() handler. For a timezone, retries or an interval the plan does not allow, call the route from an external scheduler.
- How do I keep a schedule running when my Node app scales to zero?
- You can't from inside the app: when no process is running, no timer exists. Keep one always-on worker with a minimum of one instance, use your platform's scheduler, or have an external scheduler call an HTTP route, which also wakes the app on hosts that start on request.
- Can I use these libraries with Bun or Deno?
- croner supports Node, Deno and Bun. Bun also ships Bun.cron for in-process jobs and for registering OS-level jobs in crontab, launchd or Task Scheduler. Deno has Deno.cron, which as of November 2026 still needs the --unstable-cron flag and runs in UTC. The overlap and duplicate-run advice in this guide applies to every runtime.
- How do I get alerted when a Node cron job fails or never runs?
- For a job behind an HTTP route, Crontap retries 5xx responses, timeouts and network errors, records each attempt and alerts you by email, or Slack, Discord or Telegram on paid plans, once the attempts are used up. For node-cron, crontab or queue jobs, ping a heartbeat URL when the job succeeds and its /fail URL when it throws; silence alerts once the period plus grace has passed.
