NPM Star
Collections
  1. Home
  2. Compare
  3. cron vs node-cron
NPM Compare

Compare NPM packages statistics, trends, and features

CollectionsVS Code extensionChrome extensionTermsPrivacyLinkTreeIndiehackersBig Frontendqiuyumi

Cron vs Node-cron: Task Scheduling Tools for Node.js

Both packages help developers schedule tasks to run automatically at specific times, like sending daily emails or cleaning up databases. Cron is the original package with a more traditional approach, while node-cron is a simpler, more beginner-friendly alternative. They both use the familiar cron syntax (like '* * * * *') to set up schedules, but differ in their features and ease of use.

Task Schedulingschedulingautomationtime-based-tasksbackground-jobs

Detailed Comparison

Technical Analysis

featureComparison

Both packages provide a way to schedule tasks to run at specific times or intervals. However, node-cron provides more advanced features such as support for multiple cron jobs, job prioritization, and a more flexible scheduling system.

typescriptSupport

Both packages have TypeScript definitions, but cron has better support with more detailed type definitions.

browserCompatibility

Neither package is compatible with browsers, as they are designed for server-side use.

dependencies

Both packages have minimal dependencies, with cron depending on 'async' and node-cron depending on 'moment-timezone'.

performance

Both packages have similar performance characteristics, with node-cron being slightly more efficient due to its more optimized scheduling algorithm.

Ecosystem Analysis

frameworkCompatibility

Both packages are compatible with most Node.js frameworks, including Express, Koa, and Hapi.

communityActivity

Both packages have active communities, with cron having a slightly more active community with more open issues and pull requests.

documentationQuality

Both packages have good documentation, with node-cron having more detailed and up-to-date documentation.

maintenanceStatus

Both packages are actively maintained, with cron having a more frequent release cycle.

Performance Comparison

bundleSizeAnalysis

node-cron has a smaller bundle size, making it a better choice for projects with strict size constraints.

runtimePerformance

node-cron has a slightly better runtime performance due to its optimized scheduling algorithm.

loadingTime

node-cron has a slightly faster loading time due to its smaller bundle size.

memoryUsage

Both packages have similar memory usage, with node-cron using slightly less memory due to its more efficient scheduling algorithm.

Code Examples

Scheduling a task with cron

1const cron = require('cron');
2const job = new cron.CronJob('0 0 12 * * *', function() {
3  console.log('Running task at 12:00 PM');
4});

This code creates a new cron job that runs every day at 12:00 PM.

Scheduling a task with node-cron

1const cron = require('node-cron');
2const task = cron.schedule('0 0 12 * * *', function() {
3  console.log('Running task at 12:00 PM');
4});

This code creates a new cron job that runs every day at 12:00 PM using node-cron's schedule method.

Recommendation

Summary

Both packages are suitable for scheduling tasks, but node-cron provides more advanced features and better performance.

Details

  • node-cron has a more flexible scheduling system
  • node-cron has better TypeScript support
  • node-cron has a smaller bundle size

Similar Packages

node-schedule

90%

A flexible job scheduler for Node.js. It lets you schedule jobs using simple date-based expressions, similar to cron but with a more JavaScript-friendly syntax.

Closest to cron in terms of simplicity, but with a more natural JavaScript feel. Great for developers who find cron syntax confusing.

Job Scheduler

agenda

80%

A lightweight job scheduling library for Node.js. It uses MongoDB to store jobs and can handle both one-time and repeating tasks. Think of it as a more powerful cron with a database backing.

Great for developers who need more features than basic cron, like job persistence, job queuing, and detailed job control. It's especially good if you're already using MongoDB in your project.

Job Scheduler

bree

80%

A modern job scheduler for Node.js with no dependencies. It supports workers, cron-like scheduling, and promises. It's like a modern, cleaner version of traditional cron.

Good for developers who want a modern, promise-based scheduler without external dependencies. It's newer but gaining popularity due to its clean design.

Job Scheduler

bull

70%

A Redis-based queue system for handling jobs and messages in Node.js. It can schedule jobs, handle retries, and manage job priorities. It's like a super-powered task scheduler with queue features.

Perfect when you need both scheduling and queuing features. It's more robust than cron and great for apps that need to handle many tasks reliably.

Queue & Scheduler
<p align="center"> <img src="logo.svg" alt="cron for Node.js logo" height="150"> <br /> <b>cron</b> is a robust tool for running jobs (functions or commands) on schedules defined using the cron syntax. <br /> Perfect for tasks like data backups, notifications, and many more! </p>

Cron for Node.js

Version Monthly Downloads Build Status CodeQL Status Coverage Renovate OpenSSF Scorecard Discord

🌟 Features

  • execute a function whenever your scheduled job triggers
  • execute a job external to the javascript process (like a system command) using child_process
  • use a Date or Luxon DateTime object instead of cron syntax as the trigger for your callback
  • use an additional slot for seconds (leaving it off will default to 0 and match the Unix behavior)

🚀 Installation

npm install cron

Table of Contents

  1. Features
  2. Installation
  3. Migrating
  4. Basic Usage
  5. Cron Patterns
    • Cron Syntax Overview
    • Supported Ranges
  6. API
    • Standalone Functions
    • CronJob Class
    • CronTime Class
  7. Gotchas
  8. Community
    • Join the Community
  9. Contributing
    • General Contribution
    • Submitting Bugs/Issues
  10. Acknowledgements
  11. License

⬆ Migrating

v4 dropped Node v16 and renamed the job.running property:

<details> <summary>Migrating from v3 to v4</summary>

Dropped Node version

Node v16 is no longer supported. Upgrade your Node installation to Node v18 or above

Property renamed and now read-only

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().

</details>

v3 introduced TypeScript and tighter Unix cron pattern alignment:

<details> <summary>Migrating from v2 to v3</summary>

Month & day-of-week indexing changes

  • 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.

Adjustments in CronJob

  • The constructor no longer accepts an object as its first and only params. Use CronJob.from(argsObject) instead.
  • Callbacks are now called in the order they were registered.
  • nextDates(count?: number) now always returns an array (empty if no argument is provided). Use nextDate() instead for a single date.

Removed methods

  • removed job() method in favor of new CronJob(...args) / CronJob.from(argsObject)

  • removed time() method in favor of new CronTime()

</details>

🛠 Basic Usage

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 using job.start().

For more advanced examples, check the examples directory.

⏰ Cron Patterns

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.

Supported Ranges

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".

📖 API

Standalone Functions

  • 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}`); }

CronJob Class

Constructor

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.

Methods

  • 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.

Properties

  • 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

CronTime Class

Constructor

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.

💱 Gotchas

  • 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).

đŸ€ Community

Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.

🌍 Contributing

This project is looking for help! If you're interested in helping with the project, please take a look at our contributing documentation.

🐛 Submitting Bugs/Issues

Please have a look at our contributing documentation, it contains all the information you need to know before submitting an issue.

🙏 Acknowledgements

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.

⚖ License

MIT

Node Cron

npm npm NPM Downloads Coverage Status

The node-cron module is tiny task scheduler in pure JavaScript for node.js based on GNU crontab. This module allows you to schedule task in node.js using full crontab syntax.

Node-Cron Documentation

Getting Started

Install node-cron using npm:

npm install --save node-cron

Import node-cron and schedule a task:

  • commonjs
const cron = require('node-cron'); cron.schedule('* * * * *', () => { console.log('running a task every minute'); });
  • es6 (module)
import cron from 'node-cron'; cron.schedule('* * * * *', () => { console.log('running a task every minute'); });

Cron Syntax

This is a quick reference to cron syntax and also shows the options supported by node-cron.

Allowed fields

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

Allowed values

| field | value | | ------------ | --------------------------------- | | second | 0-59 | | minute | 0-59 | | hour | 0-23 | | day of month | 1-31 | | month | 1-12 (or names) | | day of week | 0-7 (or names, 0 or 7 are sunday) |

Issues

Feel free to submit issues and enhancement requests here.

Contributing

In general, we follow the "fork-and-pull" Git workflow.

  • Fork the repo on GitHub;
  • Commit changes to a branch in your fork;
  • Pull request "upstream" with your changes;

NOTE: Be sure to merge the latest from "upstream" before making a pull request!

Please do not contribute code you did not write yourself, unless you are certain you have the legal ability to do so. Also ensure all contributed code can be distributed under the ISC License.

Contributors

This project exists thanks to all the people who contribute. <a href="https://github.com/node-cron/node-cron/graphs/contributors"><img src="https://opencollective.com/node-cron/contributors.svg?width=890&button=false" /></a>

Backers

Thank you to all our backers! 🙏 [Become a backer]

<a href="https://opencollective.com/node-cron#backers" target="_blank"><img src="https://opencollective.com/node-cron/backers.svg?width=890"></a>

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

<a href="https://opencollective.com/node-cron/sponsor/0/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/1/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/2/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/3/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/4/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/5/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/6/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/7/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/8/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/node-cron/sponsor/9/website" target="_blank"><img src="https://opencollective.com/node-cron/sponsor/9/avatar.svg"></a>

License

node-cron is under ISC License.

Dependencies Comparison

cron

Dependencies

@types/luxon~3.6.0
luxon~3.6.0

Dev Dependencies

@commitlint/cli19.8.1
@eslint/js9.27.0
@fast-check/jest2.1.1
@insurgent/commitlint-config20.0.0
@insurgent/conventional-changelog-preset10.0.0
@semantic-release/changelog6.0.3
@semantic-release/commit-analyzer13.0.1
@semantic-release/git10.0.1
@semantic-release/github11.0.2
@semantic-release/npm12.0.1
@semantic-release/release-notes-generator14.0.3
@swc/core1.11.29
@swc/jest0.2.38
@types/jest29.5.14
@types/node22.15.21
@types/sinon17.0.4
chai5.2.0
cross-env7.0.3
eslint8.57.1
eslint-config-prettier9.1.0
eslint-plugin-jest27.9.0
eslint-plugin-prettier5.4.0
husky9.1.7
jest29.7.0
lint-staged15.5.2
prettier3.5.3
semantic-release24.2.4
sinon20.0.0
typescript5.8.3
typescript-eslint7.18.0

Peer Dependencies

node-cron

Dependencies

Dev Dependencies

@eslint/js^9.26.0
@tsconfig/recommended^1.0.8
@types/chai^5.2.1
@types/expect^1.20.4
@types/mocha^10.0.10
@types/node^22.15.3
@types/sinon^17.0.4
@typescript-eslint/eslint-plugin^8.32.0
@typescript-eslint/parser^8.32.0
c8^10.1.3
chai^5.2.0
eslint^9.26.0
eslint-plugin-mocha^10.5.0
eslint-plugin-node^11.1.0
globals^16.1.0
mocha^11.1.0
sinon^20.0.0
tsup^8.4.0
tsx^4.19.3
typescript^5.8.3
typescript-eslint^8.32.0

Peer Dependencies

StarsIssuesVersionUpdatedⓘLast publish dateCreatedⓘPackage creation dateSizeⓘMinified + Gzipped size
C
cron
8,763164.3.1a month ago14 years agoinstall size 27.7 KB
N
node-cron
3,08784.1.1a month ago9 years agoinstall size 6.0 KB

Who's Using These Packages

cron

earthcalc
earthcalc

This app calculates how much a distant object is obscured by the earth's curvature.

node-cron

FileChangeMonitor
FileChangeMonitor

Continuous monitoring for JavaScript files

brand
brand

Whatsapp bot made with awesome features ❀

TravelPackHub
TravelPackHub

みんăȘăźă€Œæ”·ć€–ăžăźæŒăĄç‰©ă€ă‚’é›†ă‚ăŸă—ăŸ

aplscore
aplscore

generating tournament, team, players, match, etc.