How You Can Schedule Tasks in Node
When dealing with everyday tasks on our computer, we often have to address the same things each day. Or it can be every other day or once a week. These can be things like:
- Freeing up disk space
- Running maintenance on our computers
- Clearing logs and so on
Basically, anything that we need to do repetitively. These tasks have one thing in common: We need to take care of them periodically.
What Are Cron Jobs?
Cron jobs are one of the most useful utilities in Unix-like operating systems. They are specifically created for such cases. Itโs a time-based job scheduler that takes care of repetitive tasks.
We can use them to set up commands to run at either fixed dates or intervals. This lets us automate certain tasks such as maintenance or common administration.
How Do They Work?
Cron jobs are using the following format to execute commands. Each character represents a time unit, starting from minutes all the way to months.
An asterisk represents any value. Apart from it, we also have a set of special characters that you can use for ranges:
| Pattern | Syntax | Description
|--|--|--|
| Ranges | 1-5 | In the "day of month" field, this indicates to run every first five days of the month. This is the same as "1,2,3,4,5"
| Lists | MON,WED | In the "day of week" field, this indicates to run every Monday and Wednesday
| Steps | */5 | In the "minute" field, this indicates to run every 5 minutes
To give you some examples, imagine you need to schedule a task daily at midnight. This is how the expression would look like:
0 0 * * *
If you only need to execute a certain task once a week, for example on Sundays (or Sunday and Monday), then your syntax changes to the following:
0 0 * * Sun
0 0 * * Sun,Mon
And so on. If you are discouraged by the syntax, you can also use online generators, such as crontab.guru to create the expressions for you.
Cron Jobs in Node
To use cron jobs in node, we will need to run npm i cron
for our project. To start a new job, create a new file and add the following:
const cronJob = require('cron').CronJob;
const job = new cronJob('*/5 * * * * *', () => {
console.log('This will get executed every 5 seconds');
});
job.start();
After including the cron module, we can create new jobs using the new
keyword. This expects two mandatory parameters. One for the expression and one for a callback function to run.
You may have noticed we have 6 values instead of 5. This is because node-cron also supports seconds. Also, note that you have to start each job explicitly with job.start()
. This gives you some flexibility over running jobs. You can also specify timezones as the fifth argument:
const cronJob = require('cron').CronJob;
const job = new cronJob('*/5 * * * * *', () => {
console.log('This will get executed every 5 seconds');
}, null, true, 'Europe/London');
job.start();
The two extra parameters coming before timezone are:
onComplete
: A function that will fire when the job is stopped withjob.stop()
.start
: Specifies whether to start the cron job automatically. By default, this is set tofalse
. Which means you need to calljob.start()
to start a job.
For the list of all available timezones, you can refer to the official website of Moment.js.
To see things in action, letโs build a notification scheduler that sends out important reminders to us throughout the day.
Sending Scheduled Notifications
First, letโs see how we can schedule multiple jobs at once. Change the contents of job.js
to the following and run it with node job.js
.
const cronJob = require('cron').CronJob;
const jobs = [
{
pattern: '*/5 * * * * *',
message: 'this runs ever 5 seconds'
}, {
pattern: '*/10 * * * * *',
message: 'this runs ever 10 seconds'
}
];
jobs.forEach(job => {
new cronJob(job.pattern, () => {
console.log(job.message);
}).start();
});
Here we created an array of jobs with a pattern and a message property. We can loop through them to create a new cron job using new cronJob
and start it immediately. This should give you the following in the console:
To use push notifications in Node, we will need to npm i node-notifier
. This is because we donโt have access to the Web Push Notification API. Change job.js
to the following:
const cronJob = require('cron').CronJob;
+ const notifier = require('node-notifier');
const jobs = [
{
- pattern: '*/5 * * * * *',
- message: 'this runs ever 5 seconds'
+ pattern: '0 0 10 * * TUE',
+ message: 'Don\'t forget to take out the trash ๐๏ธ'
}, {
- pattern: '*/10 * * * * *',
- message: 'this runs ever 10 seconds'
+ pattern: '0 0 12 * * MON-FRI',
+ message: 'Now it\'s time to take a break ๐ฅฃ'
}
];
jobs.forEach(job => {
new cronJob(job.pattern, () => {
- console.log(job.message);
+ notifier.notify({
+ title: 'โฑ๏ธ Cron Job Scheduler',
+ message: job.message
+ });
}).start();
});
Here we added the notifier
module and changed the patterns. The first one will get executed every Tuesday at 10 am. The second is fired on every day of the week from Monday through Friday. If you run job.js
now, it should notify you at the right time:
Summary
If you reached this far, you should have now conquered the land of crons. Do you have suggestions on how cron can help out our daily lives? Let us know in the comments. Thank you for taking the time to read this article, happy scheduling!
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: