cron, node-cron, and node-schedule are popular npm packages used to schedule tasks (cron jobs) within Node.js applications. They allow developers to execute code at specific times or intervals using standard cron syntax or custom rules. While they share the same core purpose, they differ significantly in their API design, feature sets, and maintenance status. cron (often referred to as node-cron in older contexts but distinct as the cron package now) is a widely adopted library focusing on standard cron expression parsing. node-cron is a lightweight implementation strictly adhering to cron syntax without extra dependencies. node-schedule offers a more flexible rule-based system, supporting both cron expressions and human-readable rules, along with advanced features like job cancellation and recursion control.
When building Node.js applications, you often need to run tasks automaticallyβlike cleaning up databases, sending email digests, or generating reports. While operating systems provide system-level cron, many developers prefer handling scheduling directly within the application code for easier deployment and context access. The three main contenders for this job in the JavaScript ecosystem are cron, node-cron, and node-schedule. Let's dive into how they work and which one fits your architecture.
The most immediate difference is how you define when a job runs.
cron uses standard cron syntax exclusively. It feels familiar if you have ever edited a crontab file on Linux.
import { CronJob } from 'cron';
// Runs every minute
const job = new CronJob('* * * * *', () => {
console.log('Tick');
});
job.start();
node-cron also relies strictly on standard cron syntax. It does not support natural language or custom intervals.
import cron from 'node-cron';
// Runs every minute
cron.schedule('* * * * *', () => {
console.log('Tick');
});
node-schedule is more flexible. It supports standard cron syntax but also allows you to define rules using JavaScript objects or natural language-like strings.
import schedule from 'node-schedule';
// Standard cron syntax
schedule.scheduleJob('* * * * *', () => {
console.log('Tick via cron');
});
// Object rule: Every 5 seconds
const rule = new schedule.RecurrenceRule();
rule.second = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];
schedule.scheduleJob(rule, () => {
console.log('Tick via rule');
});
Handling time zones correctly is critical for global applications. A job meant to run at 9 AM New York time should not shift when daylight savings changes or if the server is hosted in Europe.
cron has built-in support for time zones. You can pass a time zone string directly to the job constructor.
import { CronJob } from 'cron';
// Runs at 9 AM in New York, regardless of server time
const job = new CronJob(
'0 9 * * *',
() => console.log('Good morning NY'),
null,
true,
'America/New_York'
);
node-cron does not support time zones natively. It runs based on the server's local time. If you need time zone support, you must calculate the offset manually or wrap the logic yourself, which increases the risk of errors.
import cron from 'node-cron';
// Runs based on SERVER local time only
cron.schedule('0 9 * * *', () => {
console.log('This time shifts if server moves');
});
node-schedule supports time zones similar to cron. You can pass a time zone as the third argument.
import schedule from 'node-schedule';
// Runs at 9 AM in New York
schedule.scheduleJob('0 9 * * *', 'America/New_York', () => {
console.log('Good morning NY');
});
In real-world apps, you often need to stop a job, check if it's running, or modify it dynamically.
cron provides a class-based API (CronJob) that gives you clear methods to control the lifecycle.
import { CronJob } from 'cron';
const job = new CronJob('* * * * *', task);
job.start();
// Stop temporarily
job.stop();
// Resume
job.start();
// Check status
if (job.running) {
console.log('Job is active');
}
node-cron returns a scheduled task object, but its API is slightly more limited compared to cron. You can stop it, but checking detailed status is less direct.
import cron from 'node-cron';
const task = cron.schedule('* * * * *', task);
// Stop execution
task.stop();
// Start again
task.start();
node-schedule excels here. It treats jobs as first-class citizens with robust management capabilities, including canceling and rescheduling.
import schedule from 'node-schedule';
const job = schedule.scheduleJob('* * * * *', task);
// Cancel permanently
job.cancel();
// Reschedule to a new time
job.reschedule('0 10 * * *');
// Check next execution
console.log(job.nextInvocation());
This is a critical factor for architectural decisions.
cron (the package named cron on npm) is actively maintained. It is the modern evolution of the older node-cron package (which was renamed/forked over time). It receives regular updates and security patches. This is the recommended choice for most new projects requiring standard cron.
node-cron is also maintained but focuses on being a lightweight, strict implementation. It is safe to use if you specifically want its minimal footprint, but be aware it lacks the extra features of the cron package.
node-schedule is actively maintained and stable. It has a long history and is trusted in many production environments. There are no deprecation warnings, and it remains a top choice for complex scheduling needs.
Note: Be careful not to confuse
cronandnode-cron. Historically, naming has shifted. Always check the repository URL. The packagecron(bykelektiv) is currently the most feature-rich standard implementation.
You need to send a summary email every day at 8:00 AM UTC, regardless of where your server is hosted.
cron or node-schedulenode-cron would fail here without manual offset calculations.// Using cron
const job = new CronJob('0 8 * * *', sendReport, null, true, 'UTC');
You want to ping an endpoint every 30 seconds to keep a connection alive. Simplicity is key.
node-cron*/30 * * * * *).// Using node-cron
cron.schedule('*/30 * * * * *', pingService);
Users set their own reminder times. You need to create, cancel, and update jobs dynamically based on user input.
node-schedulereschedule and cancel methods are more intuitive for dynamic workflows, and it handles one-off jobs well.// Using node-schedule
const job = schedule.scheduleJob(userDate, sendReminder);
// Later, if user changes time:
job.reschedule(newUserDate);
| Feature | cron | node-cron | node-schedule |
|---|---|---|---|
| Syntax | Standard Cron | Standard Cron | Cron + Rules + Dates |
| Time Zones | β Built-in | β Server Local Only | β Built-in |
| API Style | Class-based (CronJob) | Function/Object | Function/Job Object |
| Dynamic Control | Start/Stop | Start/Stop | Start/Stop/Cancel/Reschedule |
| Complexity | Medium | Low | High |
| Best For | Production Cron Jobs | Lightweight Scripts | Complex/Dynamic Scheduling |
Choosing the right scheduler depends on your specific needs for precision, flexibility, and complexity.
cron is the reliable workhorse π΄. If you need standard cron behavior with time zone safety and active maintenance, this is your default choice. It strikes the best balance between features and simplicity for most backend tasks.
node-cron is the minimalist π. Use it when you need a tiny footprint, don't care about time zones (or handle them externally), and just want standard cron syntax without any bells and whistles.
node-schedule is the power tool π§. If your scheduling logic is dynamicβrequiring job cancellation, rescheduling, or non-cron intervalsβthis library provides the control you need without writing custom logic.
Final Thought: For most modern Node.js applications, cron offers the safest bet for standard tasks, while node-schedule is indispensable for complex, user-driven scheduling. Avoid node-cron unless you specifically need its minimalistic constraints.
Choose cron if you need a robust, actively maintained library that strictly follows standard cron syntax and offers a good balance of features like time zone support and execution tracking. It is ideal for production environments where reliability and community support are critical, and you don't need complex non-cron scheduling rules.
Choose node-cron if you prefer a minimalistic, zero-dependency solution that strictly implements cron syntax without any extra features like time zones or complex rule definitions. It is suitable for simple, lightweight scripts or containerized environments where bundle size and simplicity are prioritized over advanced scheduling capabilities.
Choose node-schedule if your application requires flexible scheduling beyond standard cron expressions, such as recurring jobs based on natural language rules (e.g., 'every 5 minutes') or dynamic job management (canceling, rescheduling). It is the best fit for complex applications needing fine-grained control over job lifecycle and execution logic.
cron is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax.
Perfect for tasks like data backups, notifications, and many more!
child_processnpm install cron
v4 dropped Node v16 and renamed the job.running property:
Node v16 is no longer supported. Upgrade your Node installation to Node v18 or above
You can no longer set the running property (now isActive). It is read-only. To start or stop a cron job, use job.start() and job.stop().
v3 introduced TypeScript and tighter Unix cron pattern alignment:
Month Indexing: Changed from 0-11 to 1-12. So you need to increment all numeric months by 1.
Day-of-Week Indexing: Support added for 7 as Sunday.
CronJobCronJob.from(argsObject) instead.nextDates(count?: number) now always returns an array (empty if no argument is provided). Use nextDate() instead for a single date.removed job() method in favor of new CronJob(...args) / CronJob.from(argsObject)
removed time() method in favor of new CronTime()
import { CronJob } from 'cron';
const job = new CronJob(
'* * * * * *', // cronTime
function () {
console.log('You will see this message every second');
}, // onTick
null, // onComplete
true, // start
'America/Los_Angeles' // timeZone
);
// job.start() is optional here because of the fourth parameter set to true.
// equivalent job using the "from" static method, providing parameters as an object
const job = CronJob.from({
cronTime: '* * * * * *',
onTick: function () {
console.log('You will see this message every second');
},
start: true,
timeZone: 'America/Los_Angeles'
});
Note: In the first example above, the fourth parameter to
CronJob()starts the job automatically. If not provided or set to falsy, you must explicitly start the job usingjob.start().
For more advanced examples, check the examples directory.
Cron patterns are the backbone of this library. Familiarize yourself with the syntax:
- `*` Asterisks: Any value
- `1-3,5` Ranges: Ranges and individual values
- `*/2` Steps: Every two units
Detailed patterns and explanations are available at crontab.org. The examples in the link have five fields, and 1 minute as the finest granularity, but our cron scheduling supports an enhanced format with six fields, allowing for second-level precision. Tools like crontab.guru can help in constructing patterns but remember to account for the seconds field.
Here's a quick reference to the UNIX Cron format this library uses, plus an added second field:
field allowed values
----- --------------
second 0-59
minute 0-59
hour 0-23
day of month 1-31
month 1-12 (or names, see below)
day of week 0-7 (0 or 7 is Sunday, or use names)
Names can also be used for the 'month' and 'day of week' fields. Use the first three letters of the particular day or month (case does not matter). Ranges and lists of names are allowed.
Examples: "mon,wed,fri", "jan-mar".
sendAt: Indicates when a CronTime will execute (returns a Luxon DateTime object).
import * as cron from 'cron';
const dt = cron.sendAt('0 0 * * *');
console.log(`The job would run at: ${dt.toISO()}`);
timeout: Indicates the number of milliseconds in the future at which a CronTime will execute (returns a number).
import * as cron from 'cron';
const timeout = cron.timeout('0 0 * * *');
console.log(`The job would run in ${timeout}ms`);
validateCronExpression: Validates if a given cron expression is valid (returns an object with valid and error properties).
import * as cron from 'cron';
const validation = cron.validateCronExpression('0 0 * * *');
console.log(`Is the cron expression valid? ${validation.valid}`);
if (!validation.valid) {
console.error(`Validation error: ${validation.error}`);
}
constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout, waitForCompletion, errorHandler, name, threshold):
cronTime: [REQUIRED] - The time to fire off your job. Can be cron syntax, a JS Date object or a Luxon DateTime object.
onTick: [REQUIRED] - Function to execute at the specified time. If an onComplete callback was provided, onTick will receive it as an argument.
onComplete: [OPTIONAL] - Invoked when the job is halted with job.stop(). It might also be triggered by onTick post its run.
start: [OPTIONAL] - Determines if the job should commence before constructor exit. Default is false.
timeZone: [OPTIONAL] - Sets the execution time zone. Default is local time. Check valid formats in the Luxon documentation.
context: [OPTIONAL] - Execution context for the onTick method.
runOnInit: [OPTIONAL] - Instantly triggers the onTick function post initialization. Default is false.
utcOffset: [OPTIONAL] - Specifies time zone offset in minutes. Cannot co-exist with timeZone.
unrefTimeout: [OPTIONAL] - Useful for controlling event loop behavior. More details here.
waitForCompletion: [OPTIONAL] - If true, no additional instances of the onTick callback function will run until the current onTick callback has completed. Any new scheduled executions that occur while the current callback is running will be skipped entirely. Default is false.
errorHandler: [OPTIONAL] - Function to handle any exceptions that occur in the onTick method.
name: [OPTIONAL] - Name of the job. Useful for identifying jobs in logs.
threshold: [OPTIONAL] - Threshold in ms to control whether to execute or skip missed execution deadlines caused by slow or busy hardware. Execution delays within threshold will be executed immediately, and otherwise will be skipped. In both cases a warning will be printed to the console with the job name and cron expression. See issue #962 for more information. Default is 250.
from (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
start: Initiates the job.
stop: Halts the job.
setTime: Modifies the time for the CronJob. Parameter must be a CronTime.
lastDate: Provides the last execution date.
nextDate: Indicates the subsequent date that will activate an onTick.
nextDates(count): Supplies an array of upcoming dates that will initiate an onTick.
fireOnTick: Allows modification of the onTick calling behavior.
addCallback: Permits addition of onTick callbacks.
isActive: [READ-ONLY] Indicates if a job is active (checking to see if the callback needs to be called).
isCallbackRunning: [READ-ONLY] Indicates if a callback is currently executing.
const job = new CronJob('* * * * * *', async () => {
console.log(job.isCallbackRunning); // true during callback execution
await someAsyncTask();
console.log(job.isCallbackRunning); // still true until callback completes
});
console.log(job.isCallbackRunning); // false
job.start();
console.log(job.isActive); // true
console.log(job.isCallbackRunning); // false
constructor(time, zone, utcOffset):
time: [REQUIRED] - The time to initiate your job. Accepts cron syntax or a JS Date object.
zone: [OPTIONAL] - Equivalent to timeZone from CronJob parameters.
utcOffset: [OPTIONAL] - Analogous to utcOffset from CronJob parameters.
Both JS Date and Luxon DateTime objects don't guarantee millisecond precision due to computation delays. This module excludes millisecond precision for standard cron syntax but allows execution date specification through JS Date or Luxon DateTime objects. However, specifying a precise future execution time, such as adding a millisecond to the current time, may not always work due to these computation delays. It's observed that delays less than 4-5 ms might lead to inconsistencies. While we could limit all date granularity to seconds, we've chosen to allow greater precision but advise users of potential issues.
Using arrow functions for onTick binds them to the parent's this context. As a result, they won't have access to the cronjob's this context. You can read a little more in issue #47 (comment).
Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.
This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.
Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.
This is a community effort project. In the truest sense, this project started as an open source project from cron.js and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so we'll just say thanks.
Special thanks to Hiroki Horiuchi, Lundarl Gholoi and koooge for their work on the DefinitelyTyped typings before they were imported in v2.4.0.
MIT