Back to guides

Guides · April 15, 2026

Node.js cron jobs: every way to schedule Node in 2026 (with code)

crontab, node-cron, cron, croner, Bree, BullMQ, pg-boss, Agenda, serverless crons and an HTTP trigger, with working code for each. Plus a simulator for the Node-only traps: overlapping runs, a blocked event loop and the job PM2 runs four times.
crontap.com / guides
Schedule Node.js with crontab, node-cron 4.6, cron, croner, node-schedule or Bree, BullMQ job schedulers, Agenda or pg-boss, serverless crons, or an HTTP trigger. Code for each, plus the overlap, event-loop and PM2 duplicate-run traps.

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 clockExtra process to keep upCopies that fireA run due during downtimeTimezone
crontab + node script.jsNoOne per serverSkippedServer zone
node-cron, cron, croner, BreeYour app, always onOne per processSkippedPer job
BullMQ, pg-boss, AgendaWorkers plus Redis or DBOne, by designKept or configurablePer schedule
Vercel, Netlify, Cloudflare cronNoOne, best effortPlatform's callMostly UTC
HTTP route + CrontapNo, the app is up anywayOne call, any replicaRetried, then alertedPer 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>&1

Every 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. 1

    Find node by its full path, not through nvm

    nvm only loads in interactive shells, so node: command not found is the classic first failure even though Node is installed. Run which node (or nvm which 24) and paste that absolute path, or symlink one version to /usr/local/bin/node. Pin the version, so a later nvm alias default doesn't quietly change what runs at 07:00.

  2. 2

    Load the environment yourself

    Cron doesn't read your .env file. Since Node 20.6, node --env-file=.env loads it without the dotenv package; the path is relative to the working directory, which is why the line starts with cd. CRON_TZ sets the schedule's zone on cronie; on crons that don't support it, the line runs in the server's timezone.

  3. 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 -n protects 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.

LibraryVersionOverlap optionA tick that fires lateWorth knowing
node-cron4.6.0noOverlapDropped after 1 s, logged as missedEvents, distributed, file tasks in a fork
cron4.4.0waitForCompletionDropped after threshold (250 ms)CronJob.from(), Luxon timezones
croner11.0.1protectNot documentedNo dependencies; Node, Deno, Bun, browser
node-schedule2.1.2NoneNot documentedDate and object rules; first release since 2023
bree9.2.9Built in, one at a timeNot documentedEvery 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

What the job does

await fetch(), DB queries, S3 uploads

Overlap option

cron.schedule("* * * * *", buildReport);

02:00:00: Ran on time02:01:00: Ran on top of the last run02:02:00: Ran on top of the last run02:03:00: Ran on top of the last run02:04:00: Ran on top of the last run02:05:00: Ran on top of the last run02:06:00: Ran on top of the last run02:07:00: Ran on top of the last run

HTTP server, same processevent loop free

02:0002:0202:0402:0602:08
  • 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

  1. 02:00:00run 1 starts
  2. 02:01:00run 2 starts while run 1 is still going
  3. 02:02:00run 3 starts while run 2 is still going
  4. 02:03:00run 4 starts while run 3 is still going
  5. 02:04:00run 5 starts while run 4 is still going
  6. 02:05:00run 6 starts while run 5 is still going
Simulated with node-cron 4.6 rules: runs overlap by default, noOverlap skips a tick while a run is pending, and a tick that fires more than 1 second late is dropped as missed. The warnings are node-cron's own log lines.

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. cron and croner behave the same until you set waitForCompletion or protect.
  • 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 emits execution:overlap each 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. cron does the same past its 250 ms threshold. 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. upsertJobScheduler with 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 the repeat option on queue.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 pass tz, and its missed option 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:

  1. Pick one process. PM2 gives each cluster process a unique NODE_APP_INSTANCE number, 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" });
    }
  2. Let node-cron coordinate. With distributed: true, node-cron 4.6 reads NODE_CRON_RUN: set it to true on one instance and false on 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.

  3. Use a queue. BullMQ's upsert and pg-boss's throttling are built for many instances, as described above.

  4. 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.

PlatformWhere the schedule livesWhat to watchDetails
Vercel Cron Jobscrons in vercel.json, a GETUTC only; Hobby runs once a day, anywhere in the hour; no retriesVercel cron limits
Netlify scheduled functionsexport const config = { schedule }UTC; 30-second limit; can't be called by URL; not on previewsNetlify alternative
Cloudflare Workers Cron Triggerstriggers.crons in Wrangler configUTC; 5 per account on Free; changes take up to 15 minutesCloudflare limits
AWS EventBridge Schedulercron(0 7 ? * MON-FRI *) plus a zoneSix fields with ?; an IAM role for the targetLambda 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. 1

    Deploy the route with a CRON_SECRET

    Generate a value with node -p "require('node:crypto').randomBytes(32).toString('base64url')", set it as CRON_SECRET on the host, and deploy. Call the route once with curl -X POST -H "Authorization: Bearer $CRON_SECRET" https://api.example.com/internal/morning-digest and check for a 204.

  2. 2

    Create the schedule

    In Crontap, add a POST to that URL with the Authorization: Bearer ... header, set the cron to 0 7 * * 1-5 and pick America/New_York for this schedule. Runs follow that zone through daylight saving changes, so 07:00 stays 07:00.

  3. 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. 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.

One clock for every replica

Call your digest route at 07:00 New York time, once.

Paste the route's URL, add the Authorization header with your CRON_SECRET, and press Perform test before you save. However many PM2 instances or replicas sit behind it, one call goes out at 07:00; Crontap retries the failures and alerts you when the attempts run out.

Free for 2 schedules or monitors. No card.

POSThttps://api.example.com/internal/morning-digest
Active

0 7 * * 1-5America/New_York

Next run in ...

Run history

From the blog

Read the blog

Guides, patterns and product updates.

Tutorials on scheduling API calls, webhooks and automations, plus deep dives into cron syntax, timezones and reliability.

Product

Introducing Crontap status pages

Publish uptime monitors and heartbeats on a public page at crontap.page, pick a template from Clean to a split-flap departures board, and add incidents, maintenance and a badge.

Product

Slack, Discord and Telegram alerts are here

Connect a chat channel once, then route schedule, uptime and heartbeat alerts with defaults, per-job overrides and test sends. See what each alert looks like in Slack, Discord, Telegram and email.

Product Updates

Introducing AI Integrations

Transform a schedule's HTTP response with a plain-English prompt, return text or JSON, and forward it to Slack, Make, n8n, or your own endpoint. Test on any tier; saving is a Pro feature.