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:

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.

the syntax of a cron pattern
Note that cron jobs originally don’t support seconds, however cron in node does.

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
patterns.md
Copied to clipboard!

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();
job.js
Copied to clipboard!

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();
job.js
Copied to clipboard!

The two extra parameters coming before timezone are:

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();
});
job.js
Copied to clipboard!

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:

running your very first cron job 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();
  });
Copied to clipboard!

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:

Getting push notifications with cron

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!

Remove ads
Remove ads

📚 Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
🎉 Thank you for subscribing to our newsletter. x This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.