Scheduling Tasks In Node.js Made Easy With node-cron

#node
#javascript

If you're writing a Node app, you might have tasks you want to reoccur periodically. For example, run a cleaning task every Sunday night. Or check for updated weather conditions every day at 4pm.

There are some ways to solve this. You could for example use setInterval() to repeat every X seconds. Or you could a piece of your app being called with the UNIX-native cron.

In this tutorial, we're going to be using none of those. We are going to use node-cron NPM module.

About cron

As the name suggests, node-cron is based on cron which is widely used in the UNIX world do schedule tasks.

It consists of a so-called crontab file. Each line in this file represents an instruction what and when to execute and looks like this:

0 12 * * * /home/marc/task.sh

In this case, it means, run /home/marc/task.sh at midday. But let's analyze the syntax more.

Syntax

It looks complicated, but is not. The 5 numbers or * represent a piece of the time it should be executed:

# ┌───────────── minute (0 - 59)
# │  ┌───────────── hour (0 - 23)
# │  │  ┌───────────── day of the month (1 - 31)
# │  │  │  ┌───────────── month (1 - 12)
# │  │  │  │  ┌───────────── day of the week (0 - 6)
# │  │  │  │  │              (Sunday to Saturday)
# │  │  │  │  │
# │  │  │  │  │
# 30 10 25 12 * echo "merry christmas 🎄"

Important is that the values are separated by a space. Also, not that the hours are indicated with the 24-hour system.

The information for each "field" can be:

  • A number (e.g. 8)
  • A list of numbers (e.g. 8,10,20)
  • A range of numbers (e.g. 10-14)
  • A asterisk (*), which means the task should run in any instance of the field
  • Additionally it can have a "step" operator (/). This can be used to skip some values

So the example above means: "Run echo "merry christmas 🎄" every December 25th at 10:30am.

To know more about cron, check out crontab.guru. It's a website explaining the syntax and you can play around with the values.

node-cron

Let's get back to the original topic - We are going to use the same syntax as cron uses, but within our Node.js application.

Install

Install the dependency before working with it.

npm install --save node-cron

Use node-cron

The use is the follows: You schedule a task (a function) to run at a specific time, using the cron syntax as explained above:

const cron = require('node-cron')

cron.schedule('0 18 */2 * 3', () => {
  // Every second Wednesday at 6pm.
  console.log('It\s time for Whiskey Wednesday 🥃')
  console.log('https://whiskeywednesday.dev')
});

For larger applications with more scheduled tasks, I'd suggest to write the functions apart from cron and make a separate register function to schedule all of them:

const merryChristmas = () => console.log('merry christmas 🎄')
const happyNewYear = () => console.log('happy new year 🥂')
const beAnnoying = () => console.log('am i annoying yet? 😁')
const checkWeather = () => {
  // Fetch weather data
  // ...
}
const closeFrontDoor = () => {
  // Logic to close front door
  // ...
}

const registerCronJobs = () => {
  cron.schedule('30 10 25 12 *', () => merryChristmas())
  cron.schedule('0 0 1 1 *', () => happyNewYear())
  cron.schedule('* * * * *', () => beAnnoying())
  cron.schedule('0 8 * * *', () => checkWeather())
  cron.schedule('0 22 * * *', () => closeFrontDoor())
}

registerCronJobs()

Summary ✨

There you have it. The thing that needs most getting used to is the syntax. Once you got that down, scheduling tasks in Node.js takes little effort.

Photo by Aron Visuals on Unsplash