What is cron?
The cron npm package is used for scheduling tasks to be executed at specific times or intervals. It is inspired by the Unix cron scheduler and allows for the use of cron syntax to schedule tasks in a Node.js environment. This package is useful for setting up jobs like backups, sending emails, or cleaning up databases at regular intervals.
What are cron's main functionalities?
Basic Cron Job
This feature allows you to create a basic cron job that runs at a specified interval. In the provided code sample, a new CronJob is created that logs a message to the console every second.
"const CronJob = require('cron').CronJob;\nconst job = new CronJob('* * * * * *', function() {\n console.log('You will see this message every second');\n}, null, true, 'America/Los_Angeles');\njob.start();"
Time Zone Support
This feature demonstrates the ability to specify a time zone for the cron job. The code sample schedules a job to run at 11:30 AM, according to the 'America/New_York' time zone, from Monday to Friday.
"const CronJob = require('cron').CronJob;\nconst job = new CronJob('00 30 11 * * 1-5', function() {\n console.log('This runs at 11:30 AM (server time) every Monday through Friday.');\n}, null, true, 'America/New_York');\njob.start();"
Dynamic Job Scheduling
This feature allows for dynamic scheduling of jobs. The schedule can be updated or changed based on certain conditions or inputs. In the example, the 'dynamicSchedule' variable can be updated to change the job's schedule.
"const CronJob = require('cron').CronJob;\nlet dynamicSchedule = '00 30 11 * * 1-5'; // This can be dynamically changed\nconst job = new CronJob(dynamicSchedule, function() {\n console.log('This job's schedule can be dynamically changed.');\n}, null, true, 'America/Los_Angeles');\njob.start();"
Other packages similar to cron
node-schedule
node-schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows for more complex scheduling and includes features like job cancellation. It is a good alternative to cron when more flexibility is required.
agenda
Agenda is a job scheduling library for Node.js that uses MongoDB for job storage. It offers more robust job management features compared to cron, such as persistence, job prioritization, and repeating jobs. It's a good choice when jobs need to be managed across server restarts or in distributed systems.
bull
Bull is a Redis-based queue system for Node.js. It is not a direct alternative to cron but can be used for scheduling through delayed jobs. It offers advanced features like job prioritization, concurrency control, and job events. Bull is suitable for applications requiring high reliability and real-time processing.
node-cron
Originally this project was a NodeJS fork of James Padolsey's cron.js.
After Craig Condon made some updates and changes to the code base this has evolved to something that has a bit of both. The cron syntax parsing is mostly James' while using timeout instead of interval is Craig's.
Additionally, this library goes beyond the basic cron syntax and allows you to supply a Date object. This will be used as the trigger for your callback. Cron syntax is still an acceptable CronTime format. Although the Cron patterns supported here extend on the standard Unix format to support seconds digits, leaving it off will default to 0 and match the Unix behavior.
If You Are Submitting Bugs/Issues
Because we can't magically know what you are doing to expose an issue, it is best if you provide a snippet of code. This snippet need not include your secret sauce, but it must replicate the issue you are describing. The issues that get closed without resolution tend to be the ones without code examples. Thanks.
Versions and Backwards compatibility breaks:
As goes with semver, breaking backwards compatibility should be explicit in the versioning of your library. As such, we'll upgrade the version of this module in accordance with breaking changes (I'm not always great about doing it this way so if you notice that there are breaking changes that haven't been bumped appropriately please let me know). This table lists out the issues which were the reason for the break in backward compatibility.
Node Cron Ver | Issue # |
1.0.0 | |
Usage (basic cron usage):
var CronJob = require('cron').CronJob;
new CronJob('* * * * * *', function() {
console.log('You will see this message every second');
}, null, true, 'America/Los_Angeles');
Note - You need to explictly start a job in order to make it run. This gives a little more control over running your jobs.
Available Cron patterns:
Asterisk. E.g. *
Ranges. E.g. 1-3,5
Steps. E.g. */2
Read up on cron patterns here. Note the examples in the
link have five fields, and 1 minute as the finest granularity, but this library
has six fields, with 1 second as the finest granularity.
Cron Ranges
When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not.
- Seconds: 0-59
- Minutes: 0-59
- Hours: 0-23
- Day of Month: 1-31
- Months: 0-11
- Day of Week: 0-6
Another cron example
var CronJob = require('cron').CronJob;
var job = new CronJob('00 30 11 * * 1-5', function() {
}, function () {
},
true,
timeZone
);
Another example with Date
var CronJob = require('cron').CronJob;
var job = new CronJob(new Date(), function() {
}, function () {
},
true,
timeZone
);
For good measure
var CronJob = require('cron').CronJob;
var job = new CronJob({
cronTime: '00 30 11 * * 1-5',
onTick: function() {
},
start: false,
timeZone: 'America/Los_Angeles'
});
job.start();
How to check if a cron pattern is valid:
try {
new CronJob('invalid cron pattern', function() {
console.log('this should not be printed');
})
} catch(ex) {
console.log("cron pattern not valid");
}
How to check if a job is running
var cron = require('cron');
var job1 = new cron.CronJob({
cronTime: '* * * * *',
onTick: function() {
console.log('job 1 ticked');
},
start: false,
timeZone: 'America/Los_Angeles'
});
var job2 = new cron.CronJob({
cronTime: '* * * * *',
onTick: function() {
console.log('job 2 ticked');
},
start: false,
timeZone: 'America/Los_Angeles'
});
console.log('job1 status', job1.running);
console.log('job2 status', job2.running);
job1.start();
console.log('job1 status', job1.running);
console.log('job2 status', job2.running);
Install
From source: `npm install`
From npm: `npm install cron`
API
Parameter Based
CronJob
constructor(cronTime, onTick, onComplete, start, timezone, context, runOnInit)
- Of note, the first parameter here can be a JSON object that has the below names and associated types (see examples above).
cronTime
- [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.onTick
- [REQUIRED] - The function to fire at the specified time.onComplete
- [OPTIONAL] - A function that will fire when the job is complete, when it is stopped.start
- [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call job.start()
in order to start the job (assuming job
is the variable you set the cronjob to). This does not immediately fire your onTick
function, it just gives you more control over the behavior of your jobs.timeZone
- [OPTIONAL] - Specify the timezone for the execution. This will modify the actual time relative to your timezone. If the timezone is invalid, an error is thrown. You can check all timezones available at Moment Timezone Website.context
- [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call this.stop()
. However, if you change this you'll have access to the functions and values within your context object.runOnInit
- [OPTIONAL] - This will immediately fire your onTick
function as soon as the requisit initialization has happened. This option is set to false
by default for backwards compatibility.
start
- Runs your job.stop
- Stops your job.
CronTime
constructor(time)
time
- [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.
Contributors
License
MIT