Use the cron npm package ( npm install cron) for second-precision scheduled tasks in Node.js.
cron job, node-cron, schedule task, cron expression, cron pattern, scheduled job, npm install cron, CronJob, CronTime.
ts
import { CronJob } from 'cron';
const job = new CronJob(
'0 */5 * * * *', // every 5 minutes
() => console.log('Running every 5 minutes'),
null, // onComplete
true, // start immediately
'Asia/Shanghai' // timeZone
);
Or use the object form:
ts
const job = CronJob.from({
cronTime: '0 0 9 * * 1', // 9am every Monday
onTick: () => sendReport(),
start: true,
timeZone: 'Asia/Shanghai'
});
job.stop(); // halt
job.start(); // resume
The library uses 6 fields (second-precision), unlike standard 5-field Unix cron:
text
second minute hour day-of-month month day-of-week
0-59 0-59 0-23 1-31 1-12 0-7
TokenMeaning*Any value (every second/minute/etc.)1,3,5List of values1-5Range (inclusive)*/5Every N steps
Use first 3 letters for month/day-of-week (case-insensitive):
"jan,mar,dec", "mon,wed,fri"
Day-of-week: 0 or 7 is Sunday.
ExpressionMeaning*/10 * * * * *Every 10 seconds0 * * * * *Every minute on the second0 0 * * * *Every hour0 0 9 * * *Daily at 9:00 AM0 30 9 * * 1-59:30 AM Mon-Fri0 0 0 1 * *Midnight on the 1st of every month
ParamRequiredDescriptioncronTime[OK]Cron pattern string, Date, or Luxon DateTime``onTick[OK]Callback functiononCompleteCalled when job stops via job.stop()``startAuto-start. Default false``timeZoneIANA zone string (e.g. 'Asia/Shanghai')context``this context for onTick``runOnInitFire onTick immediately on initwaitForCompletionIf true, skip ticks while callback is still runningerrorHandlerCatch exceptions in onTick``nameJob identifier for debuggingthresholdMissed-deadline tolerance in ms. Default 250
Do NOT pass utcOffset together with timeZone -- they conflict.
CronJob.from(obj) (static) -- Create with named paramsjob.start() / job.stop() -- Start/stopjob.nextDate() -- Next execution as Luxon DateTimejob.nextDates(n) -- Array of next N datesjob.lastDate() -- Last execution datejob.setTime(cronTime) -- Change schedulejob.addCallback(fn) -- Add another onTick callbackjob.isActive -- Whether job is runningjob.isCallbackRunning -- Whether onTick is currently executingts
import * as cron from 'cron';
// When will this cron expression fire next?
const dt = cron.sendAt('0 0 * * *');
console.log(dt.toISO());
// How many ms until next execution?
const ms = cron.timeout('0 0 * * *');
// Validate an expression
const { valid, error } = cron.validateCronExpression('0 0 * * *');
+1 on all month values.waitForCompletion: true for async callbacks to prevent overlap.Wrap async work directly -- waitForCompletion prevents overlapping runs:
ts
const job = CronJob.from({
cronTime: '*/30 * * * * *',
onTick: async () => {
await fetchData();
await processData();
},
waitForCompletion: true,
start: true
});
See references/api_reference.md for the complete API documentation including CronTime class, all method signatures, and migration notes.