Node Schedule

2.1.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Schedules a recurring job using cron syntax and a one-time job for a future date, demonstrating job creation, event handling, and basic usage.

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);
// });

view raw JSON →