Node Schedule
Node Schedule is a robust and flexible job scheduler for Node.js, designed for time-based scheduling rather than simple intervals. It enables developers to execute arbitrary functions at specific dates and times, supporting intricate recurrence rules similar to cron, as well as one-off scheduled events. The current stable version is 2.1.1. The library differentiates itself by using only a single timer for all scheduled jobs, optimizing resource usage. Unlike traditional `cron`, it offers cross-platform support, including Windows, due to its JavaScript implementation. It's crucial to understand that `node-schedule` is an in-process scheduler, meaning jobs only run as long as the Node.js process is active and are not persisted across application restarts. For persistent or distributed job scheduling, alternatives like Agenda or Bree should be considered.
Common errors
-
TypeError: scheduleJob is not a function
cause Attempting to use `scheduleJob` from an incorrect import or `require` pattern, often due to CommonJS vs. ESM module differences or improper destructuring.fixEnsure you are using `import { scheduleJob } from 'node-schedule';` for ESM or `const schedule = require('node-schedule'); schedule.scheduleJob(...)` for CommonJS. -
My scheduled jobs are not running after I restart my application.
cause `node-schedule` is an in-process scheduler, meaning all scheduled jobs are stored in memory and are lost when the Node.js process exits.fixFor jobs that must persist across application restarts, use a durable job scheduler like `Agenda` or `Bree`, or consider system-level `cron`. -
Jobs are running at unexpected times or missing executions.
cause This can occur if the cron pattern is misunderstood, the system clock changes, or the Node.js event loop is blocked for extended periods by synchronous, CPU-intensive tasks.fixDouble-check your cron pattern against standard cron format. Ensure that your job callbacks are asynchronous or quickly executed to avoid blocking the event loop. For complex or long-running tasks, consider offloading them to worker threads or separate processes. -
My application is consuming increasing amounts of memory over time, particularly with many one-off jobs.
cause Versions of `node-schedule` prior to 2.0.0 had known memory leak issues, especially with one-off jobs that were not properly de-referenced.fixUpgrade to `node-schedule` version 2.0.0 or later, as these issues were addressed in that release.
Warnings
- breaking Version 2.0.0 dropped official support for Node.js versions older than 6. Running on older versions may lead to unexpected behavior or failures.
- breaking In version 2.0.0, direct support for 'job objects' as arguments to `scheduleJob` was removed. The API now primarily expects functions or a `Job` instance. Refer to `UPGRADING.md` for detailed migration steps.
- gotcha `node-schedule` is an in-process scheduler; jobs are transient and only persist as long as your Node.js application is running. Scheduled jobs will be lost upon application restart.
- gotcha This library is optimized for time-based, complex scheduling (e.g., 'every third Tuesday') rather than simple interval-based tasks (e.g., 'every 5 minutes'). While possible, simpler interval scheduling might be better handled by `toad-scheduler` or `setInterval`.
- gotcha The `canceled` event, emitted when an invocation is canceled before execution, uses the American spelling 'canceled' (single 'L').
Install
-
npm install node-schedule -
yarn add node-schedule -
pnpm add node-schedule
Imports
- scheduleJob
import scheduleJob from 'node-schedule';
import { scheduleJob } from 'node-schedule'; - Job
import { Job } from 'node-schedule'; - All exports (CommonJS)
const { scheduleJob } = require('node-schedule');const schedule = require('node-schedule');
Quickstart
import { scheduleJob } from 'node-schedule';
// Schedule a job using cron syntax
const cronJob = scheduleJob('*/5 * * * * *', function(){
console.log('Cron job ran: The answer to life, the universe, and everything!');
});
cronJob.on('success', (result) => {
console.log(`Cron job successful with result: ${result}`);
});
cronJob.on('error', (err) => {
console.error(`Cron job failed: ${err.message}`);
});
// Schedule a job for a specific date/time
const now = new Date();
const futureDate = new Date(now.getTime() + 10 * 1000); // 10 seconds from now
const dateJob = scheduleJob(futureDate, function(){
console.log('Date job ran: This job fired exactly at the scheduled time!');
});
dateJob.on('success', (result) => {
console.log(`Date job successful with result: ${result}`);
});
dateJob.on('canceled', (scheduledTime) => {
console.log(`Date job canceled before execution, scheduled for ${scheduledTime}`);
});
console.log(`Scheduled cron job to run every 5 seconds. Current time: ${now.toLocaleTimeString()}`);
console.log(`Scheduled date job to run at: ${futureDate.toLocaleTimeString()}`);
// Example of canceling a job (uncomment to test)
// setTimeout(() => {
// dateJob.cancel();
// console.log('Date job explicitly canceled.');
// }, 5000);
// Graceful shutdown (requires '2.1.0' or newer)
// process.on('SIGTERM', async () => {
// console.log('SIGTERM received, initiating graceful shutdown...');
// await scheduleJob.gracefulShutdown();
// console.log('All scheduled jobs stopped. Exiting.');
// process.exit(0);
// });