DEV Community

Cover image for node-cron: Automation in node.js
Evan Loria
Evan Loria

Posted on • Edited on

2

node-cron: Automation in node.js

Introduction

Automation is vital in a Node.js environment. The NPM node-cron package allows developers to schedule tasks to run at regular intervals, automating anything from database backups to daily reports. This is achieved using cron syntax, a standard format used to define the schedule in which a job should run. Automating tasks within an application saves time, increases efficiency, and removes human error from repetitive or tedious tasks.

Use Cases

node-cron is great for scheduling jobs that need to be run at regular intervals. These tasks may include system maintenance, data processing and management, or removing temporary files to save disk space and system memory. Any job that needs to run routinely can be done so reliably with node-cron.

Crontab and Cron Syntax

Crontab, which is short for 'cron table', is a file used in Unix-like systems to store scheduled tasks. node-cron uses the same syntax for defining the intervals for application tasks. Cron syntax is a string of 5 date/time fields that tell the system when the jobs should be executed.

Fields

  • minute: 1-59
  • hour: 0-23
  • day of month: 1-31
  • month: 1-12
  • day of week: 0-7 (Sunday is 0 and 7)

node-cron offers an optional seconds field that is placed at the beginning of the cron expression. This is not standard for implementations of crontab syntax.
An asterisk (*) is used to represent any possible value of the field. For example, the following cron expression would run a task every minute:
* * * * *
This cron expression runs a task everyday at 12:00 pm:
0 12 * * *

Rather than using numbers to represent the month and day of the week, these fields can be spelled out or abbreviated.
These fields are not case sensitive.

'* * * january MON' // Every monday in january
'* * * jan monday' // Every monday in janaury
Enter fullscreen mode Exit fullscreen mode

In addition, more than one option can be given to a field by supplying a comma separated list.

'0,15 12,1 * * MON,WED' 
Every Mon & Wed at 12:00, 12:15, 1:00, and 1:15
Enter fullscreen mode Exit fullscreen mode

Cron Syntax

Ranges and Steps

node-cron allows for ranges and steps to be applied to the fields. Ranges are applied using a dash (-) and steps are supplied with a slash (/) followed by the step to increment by. For example, to run a task only during the work week (Monday to Friday), you could use MON-FRI in the day of the week field. Similarly, to run a task every minute from minute 30 through minute 45 of an hour, use the expression '30-45 * * * *'.

Every minute between 12:00 and 12:30 Mon-Fri
'0-30 12 * * MON-FRI' 
At midnight on the 1st of every month January-June
'0 0 1 1-6 *'
Every 5 minutes on Monday
'*/5 * * * Mon'
Every 2 months at 12:00 pm
'0 12 * */2 *'
Enter fullscreen mode Exit fullscreen mode

Steps can also be applied to ranges

Every other day, every other month between Jan-Aug every 3 hours between 6:00am and 12:00pm
'0 6-12/3 * jan-aug/2 */2'
Enter fullscreen mode Exit fullscreen mode

Hash Operator (#)

The hash operator is used to schedule a task on the nth occurrence of a day of the week within a given month.

'0 0 * * 1#3' // At midnight the 3rd Monday of every month
'* * * 11 thu#4' // The 4th Thursday of November
Enter fullscreen mode Exit fullscreen mode

Scheduling Tasks

Once you understand cron syntax, you are able to schedule tasks to run within your Node.js application. Install the package using NPM.
npm install node-cron
Import cron into the file.

const cron = require('node-cron');
// OR
import cron from 'node-cron';
Enter fullscreen mode Exit fullscreen mode

Once you've installed and imported cron into your project use the schedule method to schedule the interval on which a task should run.
The schedule method takes two arguments, and an optional third argument: the cron expression string, and the function to execute. This example will execute a function to log 'Hello' to the console every 10 minutes.

import cron from 'node-cron';
cron.schedule('*/10 * * * *', () => {
   console.log('Hello');
}
Enter fullscreen mode Exit fullscreen mode

Options Paramter

The schedule method also accepts an options object. This parameter can set if the task is scheduled or not, and also tell node-cron what timezone to use to schedule tasks.

  • scheduled: boolean to set if the created task is scheduled. Defaults to true
  • timezone: string of the timezone to schedule tasks. See IANA Timezone Database for possible values

Task Methods

If you set a task equal to the invocation of the schedule method, you are able to use methods of that task.

const task = cron.schedule('* * * * *', taskFunction);
Enter fullscreen mode Exit fullscreen mode
  • task.start() starts the scheduled task
  • task.stop() stops the scheduled task (must be restarted to run)
  • task.validate(cronExpression) validates a given cron expression

Scheduling Tasks

In order for the application to run tasks, the server must read the file that the tasks are defined in. This means to import (or require) your task file in your server file. Alternatively, you could define your tasks directly on your server's app.js or index.js file. It is generally considered good practice to separate your tasks into a different file. This allows for better organization and maintainability.

Conclusion

node-cron provides a way for scheduling tasks within Node.js applications. By understanding cron syntax and utilizing the available options, you can improve efficiency, and save valuable time.

Sources

node-cron npm
node-cron docs

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay