How to run Cron Jobs in Node.js ?

Hey Everyone,

In this article, we will learn how to use the node-cron library to schedule cron jobs in several Node.js demo applications. node-cron is a Node module that is made available by npm and you can use it to schedule jobs to run at specific times or intervals.

To schedule jobs using node-cron, we need to invoke the method cron.schedule() method.

Let’s start by creating a node application and installing dependencies.

Create a folder and name it Node-Cron. Open the folder with Visual Studio Code. Once inside the VS Code, open the terminal.

Create a package.json file by running:

npm init -y

Once created, Execute the following command to install express, node-cron dependencies in your node js app:

npm i express node-cron

After installing the above dependencies, create an index.js file, So go to your app root directory and create it.
Now put the below code inside it:

const express = require("express");
const cron = require("node-cron");
const fs = require("fs");
app = express();

cron.schedule("*/15 * * * * *", function () {
    let data = `${new Date().toUTCString()} : Server is working\n`;
    fs.appendFile("logs.txt", data, function (err) {
        if (err) throw err;
        console.log("****************");
        console.log("Running a task every 15 seconds");
    });
});

app.listen(3000, () => {
    console.log("Server Start");
});

Here We will use */15 * * * * * cron job, which means our application runs every 15 seconds. You can also set up this cron job in your own way.

Now, Run node index.js in the terminal and it will create a new file logs.txt, every 15 seconds it creates a new entry in that file.

Output:

Also check, Send Mail In Node.Js Using HTML Templates

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories