Welcome folks today in this blog post we will be building a cron job task scheduler
in node.js using node-cron
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library using the below command as shown below
npm i node-cron
After installing the library make an index.js
file for your node.js app and copy paste the below code
Now we will be executing the tasks every minute
in node.js as shown below
1 2 3 4 5 |
var cron = require('node-cron'); cron.schedule('* * * * *', () => { console.log('running a task every minute'); }); |
As you can see we are importing the node-cron
module and then we are using the schedule
method to schedule the tasks to run every minute. These * represents the different sets of time available in node-cron module.
1 2 3 4 5 6 7 8 9 |
# ┌────────────── 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) |
Using Multiple Values
You can even provide multiple time intervals to run the node.js
code using this cron module as shown below
1 2 3 4 5 |
var cron = require('node-cron'); cron.schedule('1,2,4,5 * * * *', () => { console.log('running every minute 1, 2, 4 and 5'); }); |
Or you can even provide the range values as well
1 2 3 4 5 |
var cron = require('node-cron'); cron.schedule('1-5 * * * *', () => { console.log('running every minute to 1 from 5'); }); |