Node.js Cron Job Scheduler

4.4.0 · active · verified Sun Apr 19

The `cron` library for Node.js provides a robust solution for scheduling tasks (functions or external commands) using the familiar cron syntax, with support for second-level precision. The current stable version is 4.4.0, demonstrating active development with regular patch and minor releases, alongside beta releases for upcoming major versions like v5. Key differentiators include its flexibility in defining schedules using cron strings, standard JavaScript `Date` objects, or `Luxon DateTime` objects, comprehensive TypeScript support, and features for managing job lifecycle (start, stop, handling unexpected termination). It is designed for long-running Node.js applications and has evolved through major versions, introducing stricter cron pattern adherence and API refinements.

Common errors

Warnings

Install

Imports

Quickstart

Schedules a function to run every second using a cron string and demonstrates basic job creation and immediate start.

import { CronJob } from 'cron';

// This job runs every second, logging a message to the console.
// The cronTime pattern '* * * * * *' specifies: second, minute, hour, day of month, month, day of week.
const job = new CronJob(
	'* * * * * *', // cronTime: run every second
	function () {
		const now = new Date();
		console.log('You will see this message every second:', now.toLocaleTimeString());
	}, // onTick: function to execute when the job runs
	null, // onComplete: function to execute when the job stops (optional)
	true, // start: boolean to start the job immediately
	'America/Los_Angeles' // timeZone: specify a timezone (optional)
);

console.log('Cron job scheduled and started. It will log a message every second. Press Ctrl+C to stop the process.');

// You can stop the job at any time using job.stop().
// For example, to stop after 10 seconds:
// setTimeout(() => {
//   job.stop();
//   console.log('Cron job stopped after 10 seconds.');
// }, 10000);

view raw JSON →