Node.js Cron Jobs By Examples

Node.js Cron Jobs By Examples

In this article, we’ll look at how to create and use Cron jobs in Node applications.

In this article, we’ll look at how to create and use Cron jobs in Node applications.

Ever wanted to do specific things on your application server at certain times without having to physically run them yourself. You want to spend more of your time worrying about productive tasks instead of remembering that you want to move data from one part of the server to another every month. This is where Cron jobs come in.

In your Node applications, the applications of these are endless as they save.

To do this, we’ll make a simple application that automatically deletes auto-generated error.log files from the server. Another advantage of Cron jobs is that you can schedule the execution of different scripts at different intervals from your application.

Table of Contents

  1. Prerequisites
  2. Getting Started
  3. Install Node Modules
  4. Building the backend server
  5. Different intervals for scheduling tasks
  6. Use Case 2 - Backing Up Database
  7. Use Case 3 - Sending emails every n-time interval
  8. Conclusion

Prerequisites

To follow through this tutorial, you’ll need the following:

  • Node installed on your machine
  • NPM installed on your machine
  • Basic knowledge of JavaScript

    Getting Started

To get started, create a new Node application by opening your terminal and creating a new folder for your project. Then initialize it by running the commands:

    mkdir cron-jobs-node cd cron-jobs-node
    npm init -y

Install Node Modules

To make this application work we are going to need a couple of dependencies. You can install them by running the following commands:

    npm install express node-cron fs

express - powers the web server

node-cron - task scheduler in pure JavaScript for node.js

fs - node file system module

Building the backend server

Create an index.js file and then import the necessary node modules:

Related Course: Getting Started with JavaScript for Web Development

    touch index.js

Edit the index.js file to look like this:

    // index.js
    const cron = require("node-cron");
    const express = require("express");
    const fs = require("fs");

    app = express();

    [...]

Now here’s where node-cron comes in. After a while, we want to delete the error log files at intervals without having to do it physically. We will use node-cron to do this. Let’s take a look a simple task first. Add the following to your index.js file:

    // index.js
    [...]
    // schedule tasks to be run on the server   
    cron.schedule("* * * * *", function() {
      console.log("running a task every minute");
    });

    app.listen(3128);
    [...]

Now, when we run the server, we get the following result:

    > node index.js

    running a task every minute
    running a task every minute

Different intervals for scheduling tasks

With node-cron, we can schedule tasks for different intervals. Let’s see how to schedule task using different intervals. In the example above, we created a simple Cron job, the parameters passed to the .schedule() function were * * * * * . These parameters have different meanings when used:

     * * * * * *
     | | | | | |
     | | | | | day of week
     | | | | month
     | | | day of month
     | | hour
     | minute
     second ( optional )

Using this example, if we want to delete the log file from the server on the 21st of every month, we update the index.js to look like this:

    // index.js
    const cron = require("node-cron");
    const express = require("express");
    const fs = require("fs");

    app = express();

    // schedule tasks to be run on the server
    cron.schedule("* * 21 * *", function() {
      console.log("---------------------");
      console.log("Running Cron Job");
      fs.unlink("./error.log", err => {
        if (err) throw err;
        console.log("Error file succesfully deleted");
      });
    });

    app.listen("3128");

Now, when the server is run, you get the following output:

NB: To simulate the tasks, intervals were set to shorter period by setting the number of minutes in the parameter for the task scheduler You can run any actions inside the scheduler. Actions ranging from creating a file, to sending emails and running scripts. Let’s take a look at more use cases

Use Case 2 - Backing Up Database

Ensuring the accessibility of user data is very key to any business. If an unforeseen event happens and your database becomes corrupt, all hell will break loose if you don’t have any form of existing backup for your business. To save yourself the stress in the occurrence of such, you can also use Cron jobs to periodically backup the existing data in your database. Let’s take a look at how to do this.

NB: To simulate the tasks, intervals were set to shorter period by setting the number of minutes in the parameter for the task scheduler First, we need to install a node module that allows us to run shell scripts:

    npm install shelljs

And also install SQLite if you haven’t:

    npm install sqlite3

Now create a sample database by running the command:

    sqlite3 database.sqlite

To backup your database at 11:59pm every day, update your index.js file to look like this:

    // index.js
    const fs = require("fs");
    let shell = require("shelljs");
    const express = require("express");

    app = express();

    // To backup a database
    cron.schedule("59 23 * * *", function() {
      console.log("---------------------");
      console.log("Running Cron Job");
      if (shell.exec("sqlite3 database.sqlite  .dump > data_dump.sql").code !== 0) {
        shell.exit(1);
      }
      else{
        shell.echo("Database backup complete");
      }
    });
    app.listen("3128");

Now, when you run the server using the command:

    node index.js

You get the following result:

Use Case 3 - Sending emails every n-time interval

You can also use Cron jobs to keep your users up to date as to what is going on with your business by sending them emails at different intervals. For example, you can curate a list of interesting links and then send them to users every Sunday. To do something like this, you’ll need to do the following.

Install nodemailer by running the command:

    npm install nodemailer

Once that is done, update the index.js file to look like this:

    // index.js
    const cron = require("node-cron");
    const express = require("express");
    let nodemailer = require("nodemailer");

    app = express();

    // create mail transporter
    let transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: "[email protected]",
        pass: "userpass"
      }
    });

    // sending emails at periodic intervals
    cron.schedule("* * * * Wednesday", function(){
      console.log("---------------------");
      console.log("Running Cron Job");
      let mailOptions = {
        from: "[email protected]",
        to: "[email protected]",
        subject: `Not a GDPR update ;)`,
        text: `Hi there, this email was automatically sent by us`
      };
      transporter.sendMail(mailOptions, function(error, info) {
        if (error) {
          throw error;
        } else {
          console.log("Email successfully sent!");
        }
      });
    });

    app.listen("3128");

NB: To simulate the tasks, intervals were set to shorter period by setting the number of minutes in the parameter for the task scheduler Now, when you run the server using the command node index.js , you get the following result:

Conclusion

In this article, we have seen an introduction to Cron jobs and how to use them in your Node.js applications. Here’s a link to the GitHub repository. Feel free to add a suggestion or leave a comment below.

node-js

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.

Node.js Performance: Node.js vs Io.js

You may already be aware that Raygun uses Node.JS for our API nodes that receive your precious crash reporting data (we also do node.js crash reporting if you’re interested). We’ve peaked in the past at more than 110,000 requests per second coming...

Node.js Live | Node.js Docker Tutorial | Dockerizing Node.js App|Node.js Training|Edureka

🔥 Node.js Certification Training: https://www.edureka.co/nodejs-certification-training This Edureka video on 'Node.js Docker Tutorial' will help you in learn...

Node JS Complete Course PDF | Node.js

There are some Features that choose Node.js the foremost decision of programming designers.