How You Can Schedule Tasks in Node

How You Can Schedule Tasks in Node

Introduction to cron jobs
Ferenc Almasi โ€ข Last updated 2021 November 11 โ€ข Read time 6 min read
Get your weekly dose of webtips
  • twitter
  • facebook

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.

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:

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

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.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

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:

Copied to clipboard! Playground
const cronJob = require('cron').CronJob;

const job = new cronJob('*/5 * * * * *', () => {
    console.log('This will get executed every 5 seconds');
});

job.start();
job.js

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:

Copied to clipboard! Playground
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

The two extra parameters coming before timezone are:

  • onComplete: A function that will fire when the job is stopped with job.stop().
  • start: Specifies whether to start the cron job automatically. By default, this is set to false. Which means you need to call job.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.

Copied to clipboard! Playground
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

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:

Copied to clipboard!
  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:

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!

  • twitter
  • facebook
Did you find this page helpful?
๐Ÿ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

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.