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.
Install node-cron using npm: $ npm install --save node-cron
Import node-cron and schedule a task:
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
});
This is a quick reference to cron syntax and also shows the options supported by node-cron.
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
fields | values |
---|---|
second | 0-59 |
minute | 0-59 |
hour | 0-23 |
day of month | 1-31 |
month | 1-12 (or names, e.g: Jan, Feb, March, April) |
day of week | 0-7 (0 or 7 are sunday, or names, e.g. Sunday, Monday, Tue, Wed) |
var cron = require('node-cron');
cron.schedule('1,2,4,5 * * * *', () => {
console.log('running every minute 1, 2, 4 and 5');
});
var cron = require('node-cron');
cron.schedule('1-5 * * * *', () => {
console.log('running every minute to 1 from 5');
});
var cron = require('node-cron');
cron.schedule('*/2 * * * *', () => {
console.log('running a task every two minutes');
});
var cron = require('node-cron');
cron.schedule('* * * January,September Sunday', () => {
console.log('running on Sundays of January and September');
});
Or with short names:
var cron = require('node-cron');
cron.schedule('* * * Jan,Sep Sun', () => {
console.log('running on Sundays of January and September');
});