Godwin Ekuma I learn so that I can solve problems.

Scheduling tasks in Node.js using node-cron

3 min read 895

Task Scheduling and cron Jobs in Node Using node-cron

No developer wants to spend all their time on tedious tasks such as system maintenance and administration, daily database backup, and downloading files and emails at regular intervals. You’d much rather focus on productive tasks instead of keeping track of when these bothersome chores need to get done. And you’d certainly rather be asleep in your bed than up at some ungodly hour, staring bleary-eyed at a monitor as you run tasks that are best executed when server resources are being consumed at a lower rate.

That’s where task scheduling comes in.

Task scheduling enables you to schedule arbitrary code (methods/functions) and commands to be executed at a fixed date and time, at recurring intervals, or once after a specified interval. In Linux operating systems, task scheduling is often handled by utility services such as cron at the OS level. For Node.js apps, cron-like functionalities are implemented using packages such as node-cron, which bills itself as a “tiny task scheduler in pure JavaScript for NodeJs.”

The actions of cron are driven by a crontab (cron table) file, a configuration file that contains instructions to the cron daemon. The node-cron module allows you to schedule tasks in Node using the full crontab syntax.

A crontab syntax looks like this:

 # ┌────────────── second (optional)
 # │ ┌──────────── minute
 # │ │ ┌────────── hour
 # │ │ │ ┌──────── day of month
 # │ │ │ │ ┌────── month
 # │ │ │ │ │ ┌──── day of week
 # │ │ │ │ │ │
 # │ │ │ │ │ │
 # * * * * * *

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)

Using node-cron

Install node-cron using npm.

npm install --save node-cron

Task scheduling syntax

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

Take a look at the following example.

import * as cron from 'node-cron'
cron.schedule('5 * * * * *', () => {
  console.log('running a task every minute at the 5th second');
});

The asterisks (*) in positions, two, three, four, five, and six of the time specification are like file globs, or wildcards, for time divisions; they specify “every minute,” “every hour,” “every day of the month,” “every month,” and “every day of the week,” respectively.

The following code would run every day at 5:03 a.m. (3 5).

import * as cron from 'node-cron'
cron.schedule('3 5 * * *', () => {
  console.log('running a task every day at 5:03 am');
});

Task scheduling tips and tricks

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

Let’s say you want to run a particular task every Friday at 4 p.m. The code would look like this:

import * as cron from 'node-cron'
cron.schedule('0 16 * * friday', () => {
  console.log('running a task every Friday at 4:00 pm');
});

Or maybe you need to run quarterly database backups. The crontab syntax has no option for “the last day of the month,” so instead you can use the first day of the following month, as shown below.

import * as cron from 'node-cron'
cron.schedule('2 3 1 1,4,7,10 *', () => {
  console.log('running a task every quater on the first day of the month');
});

The following shows a task that runs five minutes past every hour between 10:05 a.m. and 6:05 p.m.

import * as cron from 'node-cron'
cron.schedule('5 10-18 * * *', () => {
  console.log('running a task five minutes past every hour between 10am and 6pm');
});

There may be situations where you need to run a task every two, three, or four hours. You can do so by dividing the hours by the desired interval, such as */4 for every four hours, or 0-12/3 to run every three hours between 12 a.m. and 12 p.m.

Minutes can be divided similarly. For example, the expression */10 in the minutes position means “run the job every 10 minutes.”



The task below runs five minutes every two hours between 8 a.m. and 5:58 p.m.

import * as cron from 'node-cron'
cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('running a task every two hours between 8 a.m. and 5:58 p.m.');
});

Scheduled task methods

Before we wrap up, let’s go over some key scheduled task methods.

Starting a task

When you set the scheduled option value to false, a task will be scheduled but cannot be started, even if the cron expression ticks.

To start such a task, you need to call the scheduled task start method.

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

import * as cron from 'node-cron'
const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('running a task every two hours between 8 a.m. and 5:58 p.m.');
});
task.start();

Stopping a task

If a need to stop a task from running arises, you can use the scheduled task stop method to set the scheduled option to false. The task won’t be executed unless restarted.

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

import * as cron from 'node-cron'
const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('running a task every two hours between 8 a.m. and 5:58 p.m.');
});
task.stop();

Destroying a task

The destroy method stops a task and completely destroys it.

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

import * as cron from 'node-cron'
const task = cron.schedule('*/5 8-18/2 * * *', () => {
  console.log('running a task every two hours between 8 a.m. and 5:58 p.m.');
});
task.destroy();

Conclusion

In this tutorial, we covered most of the node-cron features you’ll need to schedule tedious tasks and free yourself up for more important — and more fulfilling — work.


More great articles from LogRocket:


200’s only Monitor failed and slow network requests in production

Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. https://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.

LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. .
Godwin Ekuma I learn so that I can solve problems.

2 Replies to “Scheduling tasks in Node.js using node-cron”

  1. Nice article 🤓.

    I could not follow
    */5 8-18/2 * * * => running a task every two hours between 8 a.m. and 5:58 p.m.

    can you please explain?

Leave a Reply