After building an awesome web application using the node.js, there is a time when we have to do specific things in the application server at a certain time repetitively.

There are lots of things we have to do after building applications like system maintenance, server monitoring, database backup, sending reminder emails/SMS, administrative tasks and other important task related to web applications.

This is where cron jobs come in handy to automate repetitive tasks by scheduling them at a certain time.

In this article, we are going to learn how to use cron jobs in the node.js application to automate the repetitive tasks.

What is a Cron Job

Cron is a scheduler utility that allows you to run the scripts or perform the specific operation inside the server at a specific date or time continuously.

Cron jobs are important when some script is required to be executed at a fixed time over and over again.

When do I need a cron job in my node.js application

Well, there are lot’s of things will be going on into your application and it is very difficult to maintain and monitor those things daily with other productive tasks.

Following are the main area where you must schedule a node.js cron job to increase your productivity

  • Database backup
  • Sending newsletter
  • Report generation
  • Check the storage system
  • Check the DB inconsistent data
  • Monitoring the critical services inside the application
  • Delete the logs file
  • and lots more…

How To Setup Cron Jobs In Node.js

Ohh, that is lot’s of bogus theory, I already know these, please tell me how to set up the cron job in node.js efficiently.

Ok, no worries, there are few ways to implement the cron jobs in the node.js applications like building your own custom methods using the setTimeout or use any third-party library.

But, in this article, we are going to use third-party library node-cron – one of the best npm library available to schedule the cron jobs in node.js applications.

Using the node-cron in your node.js express application is very easy.

You can install it like any other npm libraries into the application using below command

npm install node-cron

After installing the module, you can easily import it into your node.js application and schedule the task at a certain date and time using the below code

const cron = require('node-cron');
 
cron.schedule('* * * * *', () => {
  console.log('running a task every minute');
});

Cron Methods

Let’s understand the methods used by this awesome module in more detail.

Schedule

This method schedules a given task to be executed whenever the cron expression ticks.

It has the following arguments:

  • expression string: Cron expression
  • function Function: Task to be executed
  • options Object: Optional configuration for job scheduling.

Example

cron.schedule(expression, function, options);

cron.schedule('0 1 * * *', () => {
   console.log('Running a job at 01:00 at Asia/Mumbai timezone');
 }, {
   scheduled: true,
   timezone: "Asia/Mumbai"
 });

In the above example, 0 1 * * * works as an expression, after this, there is a javascript anonymous function which executed when the expression meets the requirement and the last argument is the options which have two properties scheduled (accepts a boolean value. If set to false then the cron won’t start automatically) and timezone (accepts the timezone and will interpret the time set in the first parameter of schedule method accordingly).

How to set time in cron

With the node-cron module, we can schedule the task for different intervals. This is a quick reference to cron syntax and also shows the options supported by node-cron.

┌──────────────── second (optional) (Valid range 0-59)
| ┌────────────── minute (Valid range: 0-59)
| | ┌──────────── hour (valid range: 0-23)
| | | ┌────────── day of the month (Valid range: 1-31)
| | | | ┌──────── month (Valid range: 1-12 or names of the months)
| | | | | ┌────── day of the week (valid range: 0-7 or names of the days: both 0 and 7 denotes Sunday)
| | | | | | 
| | | | | |
* * * * * *

The cron schedule expression is very similar to crontab with an exception that it also accepts seconds field so you can schedule tasks to the second.

Some Popular Examples of Cron Jobs Schedule

Schedule cron jobs at every second

cron.schedule('* * * * * *', () => {
   console.log('Running a job at every second');
});

Schedule cron jobs at every 5 min

cron.schedule('*/5 * * * *', () => {
   console.log('Running a job at every 5 min');
});

In the above code, if we */5 replaced it with */10 or */15 then cron will run at every 10 and 15 min respectively. This is known as stepping.

Schedule cron jobs at every hour

cron.schedule('0 * * * *', () => {
    console.log('Running a job at every hour');
 });

Schedule cron jobs for daily

cron.schedule('0 0 * * *', () => {
    console.log('Runing a job daily');
 });

You can also use this schedule to run the cron jobs at every midnight and every night.

Schedule cron jobs every Sunday or any day of the week

cron.schedule('0 0 * * SUN', () => {
    console.log('Runing a job every sunday');
 });

You can use this schedule for other days of the week also, You just have to change the value of SUN to the Mon, Tue, Wed, Thu, Fri, Sat for Monday, Tuesday, Wednesday, Thursday, Friday and Saturday respectively.

Schedule cron jobs for monthly

cron.schedule('0 0 1 * *, () => {
     console.log('Runing a job At 00:00 on day-of-month 1');
  });

You can learn more about the time of cron job from crontab website.

Conclusion

In this article, we saw how easy it is to schedule a task using the cron job in node.js and use it in the express.js application.

Although, most of the things covered here, if you want to learn more then you can refer the detailed documentation here.

If you have any suggestions or feedback then feel free to comment in the comment box. If you like this article then share it with your group. 🙂

Codecademy Code Foundations
Pin It