Skip to content
jshacks.dev
Node.js

Run a cron job with setInterval and Temporal

Run a daily job at a set local time in Node.js 26 with a setInterval tick and Temporal.ZonedDateTime, so daylight saving changes never shift the schedule.

2 min read
Summarize in AI

setInterval(job, 24 * 60 * 60 * 1000) drifts: it runs every 24 hours of elapsed time, so after a daylight saving change your 02:00 job runs at 01:00 or 03:00. Ask Temporal for the next wall-clock time instead, and let a short interval check whether it has arrived.

cron.mjsJavaScript
const zone = 'Europe/Berlin';
const at = Temporal.PlainTime.from('02:00');

function nextRun(now) {
  let next = now.withPlainTime(at);
  if (Temporal.ZonedDateTime.compare(next, now) <= 0) next = now.add({ days: 1 }).withPlainTime(at);
  return next;
}

const now = Temporal.ZonedDateTime.from('2026-03-28T23:30:00+01:00[Europe/Berlin]');
const next = nextRun(now);
console.log(next.toString());
console.log(now.until(next).total('minutes'));

let due = nextRun(Temporal.Now.zonedDateTimeISO(zone));
setInterval(() => {
  const current = Temporal.Now.zonedDateTimeISO(zone);
  if (Temporal.ZonedDateTime.compare(current, due) >= 0) {
    due = nextRun(current);
    console.log('running nightly job');
  }
}, 30_000);
Text
2026-03-29T03:00:00+02:00[Europe/Berlin]
150

On 29 March 2026 Berlin skips from 02:00 to 03:00, so 02:00 does not exist. withPlainTime resolves the gap with the default compatible disambiguation and lands on 03:00, two and a half real hours later. Because every check compares wall-clock times in the zone, the job keeps its slot on both sides of the change. See Temporal.ZonedDateTime.

Temporal is a global in Node.js 26 and absent from Node.js 24. A 30 second tick means the job starts up to 30 seconds late, and a process that is down at 02:00 skips that night; for jobs that must never be missed, use a persistent scheduler or the system's cron.

Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.