Node-cron is a npm package which you can use to schedule jobs to run at specific times or intervals. It is most suitable for scheduling repetitive jobs such as email notifications, file downloads, and database backups.
For example, Github Actions uses cron syntax when scheduling a workflow to run at a specific time. Similarly, cloud platforms such as Google Cloud require cron syntax when describing job schedules.
Node-cron is written for node in pure JavaScript and it is based on GNU crontab syntax. Though it is based on crontab, our focus in this article will be on learning node-cron and cron syntax.
How to Use Node-cron to Schedule a Job
As I already mentioned above, node-cron
was written for Node and is distributed via npm. After installation using the command npm i node-cron
, it must be required into the project like any other Node package:
const cron = require("node-cron");
To schedule a job, you need to invoke the cron.schedule
method with two arguments. There is a third optional argument that you can pass to the method for additional configuration.
Below is the function signature for the cron.schedule
method.
cron.schedule(expression, function, options);
The code snippet below is an example of how you can invoke the schedule
method.
const job = cron.schedule("* * * * * *", function jobYouNeedToExecute() {
// Do whatever you want in here. Send email, Make database backup or download data.
console.log(new Date().toLocaleString());
});
The first argument you need to pass to cron.schedule
is the cron expression. You use this expression to specify the time (or times) at which the job should be executed.
This expression should be in the * * * * * *
format. You can replace each *
field with an appropriate number (or characters where possible) so that the expression describes the time at which the job should be executed.
If you pass "* * * * * *"
without replacing any *
, like in the above example, the job gets executed every second.
The second argument is a function and it is the job that gets executed when the expression in the first argument ticks.
You can do whatever you want in this function. You can send an email, make a database backup, or download data. This function gets executed when the current system time is the same as the time provided in the first argument. In the above example, I am just printing the current date.
And the third argument is an optional configuration object for job scheduling. I didn’t pass the third argument in the above example since it is optional.
Below is an example of what the third argument looks like.
{
scheduled: false,
timezone: "America/Sao_Paulo"
}
By default scheduled
is true
. If you set it to false
, you will have to schedule the job by invoking the start
method on the job
object. job
is the object returned by a call to the schedule
method.
job.start();
The default timezone
we use is for the system on which the job is scheduled. You can pass a different timezone
if you wish.
See IANA time zone database for valid values, such as Asia/Shanghai, Asia/Kolkata, America/Sao_Paulo.
Understanding Cron Expressions
The cron expression, which is the first argument to schedule
, is a string that takes the form "* * * * * *"
. We use it to describe the time at which the job should be executed. Each *
in the expression is a field and you can see the field represented by each *
in the illustration below.
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
As you can see from the above illustration, the first field is the second
field, the second field is the minute
field, and the third is the hour
field, and so on.
The table below shows the fields and their corresponding allowed values:
FIELD | ALLOWED VALUES |
---|---|
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 and 7 refer to sunday |
The job is executed when the second, minute, hour, and month fields match the current time, and when at least one of the two day fields (day of month, or day of week) match the current time. – crontab documentation
There are different ways to populate the fields in a cron expression. Each field in a Node expression can be populated using single integer values, a range of values, multiple values separated by commas, step values, or using names.
How to Use Single Integer Values to Populate a Cron Expression
You can replace each asterisk with a single integer value in the allowed range of values.
For example, passing "30 20 * * * *"
will make node-cron run your job at the thirtieth second of the twentieth minute of each hour. Since you didn’t specify a value for the hour field, node-cron interprets *
to mean every hour. The same applies to the day of the month
field, and so on.
const job = cron.schedule("30 20 * * * *", () => {
console.log(new Date().toLocaleString());
});
Similarly, passing "30 5 13 * * *"
will run your task at 1:05:30pm every day.
const job = cron.schedule("30 5 13 * * *", () => {
console.log(new Date().toLocaleString());
});
How to Use a Range of Values to Populate Cron Expressions
You an also use ranges of numbers to populate your chron expressions. A range refers to two numbers separated by the -
character. The end values are part of the range.
For example, if the hour
field is set to 2-4
, it specifies execution at hours 2, 3, and 4.
const job = cron.schedule("* 2-4 3 * *", () => {
console.log(new Date().toLocaleString());
});
In the above code snippet, I have excluded the optional second
field. It will execute your job every minute from 2 am to 4 am on the third day (because the day of the month
field has a value of 3
) of each month.
How to Use Multiple Values to Populate Cron Expressions
You can also pass multiple values separated by commas or a range of values separated by commas.
For example, passing 2,3,4
as the value of the minute
field will execute your job at minutes 2, 3, and 4.
const job = cron.schedule("2,3,4 * * * *", () => {
console.log(new Date().toLocaleString());
});
In the above code snippet, I have again excluded the optional second
field. It will execute your job at the first, second, and third minutes of each hour.
How to Use Step Values to Populate Cron Expressions
You can use step values with ranges. Following a range with /<number>
skips the number’s value through the range.
For example, using 0-8/2
in the hour
field will execute the code at 0,2,4,6
and 8
hours. You can also use step values with *
. For example */3
executes every three hours.
const job = cron.schedule("*/2 * * * *", () => {
console.log(new Date().toLocaleString());
});
In the above code snippet, the job will be executed every two minutes. Once again I’ve omitted the optional second
field.
How to Use Names to Populate Cron Expressions
For the month and day of the week fields, you can use names. These can be short or long names. For example January
or Jan
.
const job = cron.schedule("* * * January,September Sunday", () => {
console.log(new Date().toLocaleString());
});
Once again I have omitted the optional second
field. The job will run every minute on Sundays in January and September. You can also use short names like Jan, Sep
.
That’s all about the node-cron. For official documentation details refer here.