Node-cron – Schedule a Job in Node

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:

FIELDALLOWED VALUES
second0 – 59
minute0 – 59
hour0 – 23
day of month1 – 31
month1 – 12 or names
day of week0 – 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 * * * *", () =&gt; {
  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", () =&gt; {
  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.

Related Posts

secure nodejs

Securing Your Node.js Application: Best Practices and Strategies

Node.js is a popular and powerful runtime for building server-side applications with JavaScript. However, as with any web application, security should be a top priority. In this…

best nodejs framework

Best NodeJs Frameworks for Backend development in 2024

In the ever-evolving landscape of Node.js, choosing the right framework for your backend can be daunting. Express.js, Nest.js, Koa.js, and Fastify.

session-vs-token

Session-Based vs. Token-Based Authentication: Which is better?

Discover the key differences between Session-Based and Token-Based Authentication in our latest blog! Exploring concepts like security, simplicity, scalability.

how to install node.js?

How to install Node.js in mac, windows, linux?

Ready to unlock the dynamic potential of JavaScript? Buckle up, because your first step is installing Node.js, the runtime environment that fuels modern web development. Fear not, for this excerpt will guide you through a smooth installation on Windows, Linux, and macOS, transforming you into a platform-agnostic Node ninja!

Leave a Reply

Your email address will not be published. Required fields are marked *