Skip to main content

Scheduling tasks in Node.js 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.

FieldValue
second0–59
minute0–59
hour0–23
day of the month1–31
month1–12 (or names)
day of the week0–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.

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...