Skip to main content

Scheduling Tasks in Node.js with node-cron

Cron is (one of || the) most famous job scheduler out there. It is used in Unix-based operating systems.
Let’s say you have a very susceptible computer. You want to be sure you don’t forget its birthday. If we want to run echo "I love you 💻" every year at a specific date (this will output ‘I love you 💻’ in whatever environment you scheduled it in).
Here is what it would look like in cron (try to guess when is my computer’s birthday).
# ┌───────────── minute (0 - 59)
# │  ┌───────────── hour (0 - 23)
# │  │ ┌───────────── day of the month (1 - 31)
# │  │ │  ┌───────────── month (1 - 12)
# │  │ │  │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday;
# │  │ │  │ │                                   7 is also Sunday on some systems)
# │  │ │  │ │
# │  │ │  │ │
# 10 8 23 9 * echo "I love you 💻"
Every year, the 23rd of September at 8:10am the computer will get a lovely message. Please note that the date is military so if we want to celebrate the birthday at 8pm we would write:
# 10 20 23 9 * echo "I love you 💻"
The wildcard sign * means any. In this example it means any day of the week. If we wrote:
# 10 20 23 9 1 echo "I love you 💻"
It would only wish a happy birthday when the computer’s birthday is on a Monday. The wild card can be used anywhere. To run a command every hour we would do: 0 * * * *. You can translate that command into “Run command when minute === 0”. Every hour on Monday would be 0 * * * 1.
For our apps the cron jobs will be:
# Morning 💊
30 8 * * *
# Afternoon 💊
30 15 * * *
# Night 💊
15 23 * * *

Using node-cron

I didn’t choose node-cron over other Node.js cron-like libraries for any other reason that it works for what I need.
To register a task all we have to do is:
const cron = require('node-cron');
const sendBirthdayMessage = () => { console.log("I love you 💻") };

// schedule takes two arguments, cron time and the task to call when we reach that time
cron.schedule('10 20 23 9 1', sendBirthdayMessage())
Let’s incorporate it in our app.
// Each subscription is connected to a client
const allSubscriptions = {}

const registerTasks = (subscription) => {
  const endpoint = subscription.endpoint;

  // My remote machine is on UTC time and I live in Japan so I made the appropriate calculation
  const morningTask = cron.schedule('30 23 * * *', () => {
    sendNotification(subscription, JSON.stringify({ timeOfDay: 'morning' }));
  });
  const afternoonTask = cron.schedule('30 6 * * *', () => {
    sendNotification(subscription, JSON.stringify({ timeOfDay: 'afternoon' }));
  });
  const nightTask = cron.schedule('15 14 * * *', () => {
    sendNotification(subscription, JSON.stringify({ timeOfDay: 'evening' }));
  });

  allSubscriptions[endpoint] = [morningTask, afternoonTask, nightTask];
};

app.post('/subscribe', (req, res) => {
  const subscription = req.body;
  registerTasks(subscription);
  res.send('subscribed!');
});


// Allows our client to unsubscribe
app.post('/unsubscribe', (req, res) => {
  const endpoint = req.body.endpoint;
  allSubscriptions[endpoint].forEach(task => {
    // destroy allows us to delete a task
    task.destroy();
  });
  delete allSubscriptions[endpoint];
});

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...