How to Run Cron Jobs in Node.js?

You have already read tutorials on many different types of applications that can be built using Node.js, but have you wondered how we create projects like task schedulers, automated newsletter senders, message schedulers, etc. that require some system to execute tasks on a specific schedule?

Well, we can do all this by running cron jobs in Node.js. This tutorial will explain everything about the cron job, what it is, and how to achieve it in Node.js and then we will create a task scheduler using it. Let’s get started.

Understanding Cron Jobs

The term “cron jobs” originally comes from the Unix operating system. Cron is a time-based task scheduler in operating systems based on Unix like Linux, macOS, etc to periodically run tasks at specific dates and times.

Today in this article we will use npm “node-cron” to stimulate this cron job function of scheduling tasks and running at specific times. Let’s get started by understanding this module & the method required for our task.

Use node-cron to Run Scheduled Jobs in Node.js

The “node-cron” is a third-party module that can be installed in Node.js using NPM. All you need to do is, inside the project folder execute the “npm i node-cron” command. This module is considered as a task scheduler written in JavaScript based on GNU crontab and using it we can achieve what the cron job does in the Unix-based operating system. 

Syntax:

const cron = require('node-cron');

cron.schedule('* * * * *', () => {
    // Task to be executed
});

You might be confused by seeing the argument passed to this method but it is very easy.

The argument expression consists of six fields representing second (optional),  minute, hour, day of month, month, and day of week, in that order. We can pass custom inputs or use the asterisk (*) as a wildcard.

In the above syntax, we have used asterisks only, this means that the task or the callback function we passed as an argument to this method will be executed every minute, every hour, every day of the month, every month, and every day of the week.

Example:

Suppose you want to send a message to someone special on their birthday, on September 29th, at midnight 12 o’clock, you can easily do that by using the given code.

const cron = require('node-cron');

cron.schedule('0 0 29 9 * 2024', () => {
    console.log("Happy Birthday!");
});

Here we have not defined * in the position of day of the week as we have already set the day of the month (29) and month (9).

Creating a Reminder App Using node-cron

Now that we have learned all about cron jobs and node-cron, it is time to create a full-fledged application to implement the same. We will use JavaScript with Node.js to get the job done.

Step 1: Create a project folder, then create a file “app.js” to write the Node.js code and then open the project folder inside a code editor.

Step 2: Open the terminal and run the below command to install “node-cron” and “readline”

npm i node-cron readline

The “readline” module is used to read input from the command line and print output. We will use this to take input from users of the reminder time. If you want to read more about the Node.js readline module, click here.

Install node-cron and readline module

Step 3: Inside the “app.js” file write the below code.

const readline = require('readline');
const cron = require('node-cron');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Enter reminder time (DD MM YYYY HH mm): ', (answer) => {
    const [day, month, year, hour, minute] = answer.split(' ');
    const cronExpression = `${minute} ${hour} ${day} ${month} *`;

    cron.schedule(cronExpression, () => {
        console.log(`Time to do your task! It's ${hour}:${minute} on ${day}/${month}/${year}`);
        rl.close();
    });

    console.log('Reminder set successfully!');
});

Here we have first imported the “readline” & “node-cron” modules, then created an “rl” interface for input and output using the createInterface() method.

Then we used the question() method to prompt the user for input based on which an argument expression will be created and passed to our main cron.schedule() function to set the reminder, then we closed the “rl” interface and printed a success message to the console.

GitHub repository of the project, Feel free to contribute!

Step 4: Run the application by executing the command given below.

node app.js
node app.js

Enter the required information to set the reminder. For testing, I am setting it for the next minute.

Entering the required information

The reminder will automatically appear on the console at the specified time.

Reminder automatically appear

Read More: How to Build a Todo App with NodeJS (Express & EJS)

Summary 

So in short, it is possible to run cron jobs in Node.js using cron.schedule() function of the npm “node-cron” module to set tasks that run at specific times. This function takes an argument expression containing five required fields, minute, hour, day of month, month, and day of the week to set reminders for and asterisks (*) as a wildcard if any field is not necessary to pass. We hope you enjoyed reading the content.

Reference

https://www.npmjs.com/package/node-cron

Aditya Gupta
Aditya Gupta
Articles: 161