How to schedule jobs in node.js

H

Hey there, In this article we would be learning how to schedule jobs in nodejs.

There can be times where we want to schedule a job in node, like sending report email, some check etc.

Scheduling a job in node is really simple, just follow the steps along with me.

Step 0: Project Setup

First things first, let’s create a folder say myApp and open this folder in terminal or command prompt. After then run the classic command to initialise the node project.

npm init

After you have setup your project let’s move to another step and install dependencies.

Step 1: Installing DEPENDENCIES

In order to schedule our jobs in node, we need to install node-cron package and express off-course.

So, fire up your terminal and run the following command:

npm install express node-cron

Great, now you have successfully installed the dependencies and we are ready to move to next step and write some code.

Step 2: Let’s Code

Now, in your project root directory create an index.js file which is your entry point to the project.

In index.js let’s write some boilerplate code.

Pretty simple!

Now, lets understand the node-cron.

The basic syntax to use node-cron is:

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

In the above example, we are scheduling a simple console.log statement which would run every minute. How? Don’t worry, I am here to explain you.

In the above code, firstly we required the node-cron module. Then, we called the schedule method which accepts two parameters, weird looking stars and a callback function.

What are those weird looking asterisks?

Those asterisks are the way to specify the time to schedule our job. The first asterisk represents the seconds, then minute, hour, day, month and lastly week.

Now it makes sense! Right ?

Lets explore some more exmaples:

  1. Lets schedule a job that runs on  Sundays of January and September

2. A job that runs every month

Congrats! You have successfully learned how to schedule jobs in nodejs.

Here is a simple assignment for you:

You have to create a job that runs every after every 2 minutes on Sundays of January.

Post your code below in the comments section.

Thank you!

About the author

piyushlco

Add comment

Leave a Reply

By piyushlco

Most common tags

%d bloggers like this: