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) |
Install node-cron using npm.
npm install --save node-cron
cron.schedule(cronExpression: string, task: Function, options: Object)
scheduled
: A boolean
to set if the created task is scheduled (default is true
)timezone
: The timezone used for job schedulingTake 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'); });
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.'); });
Before we wrap up, let’s go over some key scheduled task methods.
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();
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();
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.
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.
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. Start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowAstro, renowned for its developer-friendly experience and focus on performance, has recently released a new version, 4.10. This version introduces […]
In web development projects, developers typically create user interface elements with standard DOM elements. Sometimes, web developers need to create […]
Toast notifications are messages that appear on the screen to provide feedback to users. When users interact with the user […]
Deno’s features and built-in TypeScript support make it appealing for developers seeking a secure and streamlined development experience.
2 Replies to "Scheduling tasks in Node.js using node-cron"
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?
Should be the same as */5 8,10,12,14,15,18 * * *