How to run Cron Jobs in Node.js ? - GeeksforGeeks

28 Jan, 2020
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:
// Importing required librariesconst cron = require("node-cron");const express = require("express");  app = express(); // Initializing app  // Creating a cron job which runs on every 10 secondcron.schedule("*/10 * * * * *", function() {    console.log("running a task every 10 second");});  app.listen(3000);
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:
// Importing required packagesconst cron = require("node-cron");const express = require("express");const fs = require("fs");  app = express();  // Setting a cron jobcron.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);
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:
// Importing packagesconst cron = require("node-cron");const express = require("express");const nodemailer = require("nodemailer");  app = express();  // Calling sendEmail() function every 1 minutecron.schedule("*/1 * * * *", function() {sendMail();});  // Send Mail function using Nodemailerfunction 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);
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:
Node.js-Misc
Technical Scripter 2019
Node.js
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Node.js fs.writeFile() Method
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Express.js res.sendFile() Function
Mongoose | findByIdAndUpdate() Function
Top 10 Front End Developer Skills That You Need in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript