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

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...