How to run Cron Jobs in Node.js ?

Cron Jobs: These are the tasks that run periodically by the operating system. Users can schedule commands the OS will run these commands automatically according to the given time. It is usually used for system admin jobs such as backups, logging, sending newsletters, subscription emails and more.

Prerequisites:

  • Node.js installed
  • NPM installed
  • Basic knowledge of Node.js syntax

We will use a package called node-cron which is a task scheduler in pure JavaScript for node.js. We are also using express as a server. Install the required packages using the command

npm install express node-cron

Syntax:

cron.schedule("* * * * *", function() {
    // Task to do
});

Time formatting for Cron jobs:



Descriptors with their ranges:

  • Seconds (optional): 0 – 59
  • Minute: 0 – 59
  • Hour: 0 – 23
  • Day of the Month: 1 – 31
  • Month: 1 – 12
  • Day of the week: 0 – 7 (0 and 7 both represent Sunday)

Examples:

  • (*/10 * * * *) – Runs on every 10 minutes
  • (* * 21 * *) – Runs 21th of every month
  • (0 8 * * 1) – Runs 8 AM on every Monday

Example: Create a new file named index.js and add the following code:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing required libraries
const cron = require("node-cron");
const express = require("express");
  
app = express(); // Initializing app
  
// Creating a cron job which runs on every 10 second
cron.schedule("*/10 * * * * *", function() {
    console.log("running a task every 10 second");
});
  
app.listen(3000);

chevron_right


Run the file using command node index, you will see the output like below:

Writing to a log file: Cron jobs can be used to schedule logging tasks in a system. We can log server status for a given time for monitoring purposes.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing required packages
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
  
app = express();
  
// Setting a cron job
cron.schedule("*/10 * * * * *", function() {
  
    // Data to write on file
    let data = `${new Date().toUTCString()} 
                : Server is working\n`;
      
    // Appending data to logs.txt file
    fs.appendFile("logs.txt", data, function(err) {
          
        if (err) throw err;
          
        console.log("Status Logged!");
    });
});
  
app.listen(3000);

chevron_right


After running above file for 30-40 seconds, you will see a file created named logs.txt having content somewhat similar to the following:

Monthly Newsletters: Sending monthly newsletters are also a use case for cron jobs in which an email will be sent to the users monthly with the latest products or blog information on the website.



You can learn more about sending email in Node.js here.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing packages
const cron = require("node-cron");
const express = require("express");
const nodemailer = require("nodemailer");
  
app = express();
  
// Calling sendEmail() function every 1 minute
cron.schedule("*/1 * * * *", function() {
sendMail();
});
  
// Send Mail function using Nodemailer
function sendMail() {
    let mailTransporter = nodemailer.createTransport({
        service: "gmail",
        auth: {
        user: "<your-email>@gmail.com",
        pass: "**********"
        }
    });
      
    // Setting credentials
    let mailDetails = {
        from: "<your-email>@gmail.com",
        to: "<user-email>@gmail.com",
        subject: "Test mail using Cron job",
        text: "Node.js cron job email"
           + " testing for GeeksforGeeks"
    };
      
      
    // Sending Email
    mailTransporter.sendMail(mailDetails, 
                    function(err, data) {
        if (err) {
            console.log("Error Occurs", err);
        } else {
            console.log("Email sent successfully");
        }
    });
}
  
app.listen(3000);

chevron_right


The above script will send emails every minute.

Note: Open this link to Allow less secure apps: ON.

Now run the file using node index.js, you will see the output like below:

In console:

In Gmail Inbox:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.