Introduction

When dealing with recurring events, we need to schedule events regularly. It can be daily, weekly, monthly or any other customized form.

Basically, these tasks have one thing in common: We need to take care of them periodically.

In Linux operating systems, task scheduling is often handled by utility services such as cron at the OS level. We can use them to set up commands to run at either fixed dates or intervals.

One method for implementing cron on a Node.js server is by using the node-cron module. This library uses the crontab syntax.
A crontab syntax looks like this:

Crontab syntax

Allowed cron values include the following.

Field

Value

second

0–59

minute

0–59

hour

0–23

day of the month

1–31

month

1–12 (or names)

day of the week

0–7 (or names, 0 or 7 are sunday)

In this article, you will use node-cron to schedule recurring events.


Scheduling recurring events using node-cron

Step 1: Install node-cron

To use cron jobs in node, we will need to install node-cron for our project.

Install node-cron using npm.

npm install --save node-cron

Then add the following code to import the node-cron module.

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

Task scheduling syntax:

After including the cron module, we can create new jobs using the cron.schedule syntax. This expects three mandatory parameters as follows.

cron.schedule(cronExpression: string, task: Function, options: Object)

Options:

scheduled - A boolean to set if the created task is scheduled (default is true)

timezone - The timezone used for job scheduling

Now that we’ve got the basics covered, let’s do something more interesting.

Step 2: Get Input data

First, let’s see what are the inputs that we need to create a custom cron expression.

inputs : 
	{
    		jobId,
    		recurringType,
    		dayOfMonth,
    		dayOfWeek,
    		hour,
    		minute,
   	}

Step 3:  Generate cron pattern

By using above input parameters we can create a cron expression. This expression then can be fed to the cron.schedule.

const CronPaternGenerator = ({
  recurringType,
  dayOfWeek,
  dayOfMonth,
  hour,
  minute,
}) => {
  try {
    switch (recurringType) {
      case RECURING_TYPES.DAILY: {
        return `0 ${minute} ${hour} * * *`;
      }
 
      case RECURING_TYPES.WEEKLY: {
        return `0 ${minute} ${hour} * * ${ dayOfWeek }`;
      }
      case RECURING_TYPES.MONTHLY: {
        return `0 ${minute} ${hour} ${ dayOfMonth } * *`;
      }
      default:
        return null;
    }
  } catch (error) {
    console.log(error);
    return null;
  }
};

Step 4: Create cron job

Then create a cron job using cron.schedule syntax for the created cron pattern. Finally store the created cron job id so that to take further control actions.

let cronJobs = {};
 
async function createCronJob({
  jobId,
  recurringType,
  dayOfMonth,
  dayOfWeek,
  hour,
  minute,
}) {
  return new Promise(async (resolve, reject) => {
    try {
      const pattern = CronPaternGenerator({
        jobId,
        recurringType,
        dayOfMonth,
        dayOfWeek,
        hour,
        minute,
      });
      const task = cron.schedule(pattern, () => {
        console.log('task is running', pattern);
      });
      cronJobs[jobId] = task;
      resolve({});
    } catch (err) {
      reject(err);
    }
  });
}

Great!

Now all you have to do is run your js file and you should see ‘task is running {your pattern}’ being printed to the console according to your schedule.

Summary

In this article, you learned how to use node-cron to schedule recurring events on a Node.js server. You were introduced to the broader concept of automating repetitive tasks in a consistent and predictable manner. This concept can be applied to your current and future projects.