Loading

How to Setup Cron Job in Node.js

How to Setup Cron Job in Node.js

Overview

Cron is a task which allows running automated commands at specific date & time. This is developer favourite because it helps to set up the task-specific script in the background which will run on defined time. So In this post, we will learn how to a setup cron job in node.js.

Prerequisites

  • Nodejs Installed system
  • NPM (Node package manager) installed
  • Basic knowledge of node.js

We will use node-cron module which allows you to schedule task in node.js using full crontab syntax. So go to npm website for a complete reference of the node-cron module

https://www.npmjs.com/package/node-cron

I have written a complete guide about cron-setup in Linux So please go through this article if you don't have any knowledge about the cron.

How to Setup Cron Job on Linux

Let's start We will use express & node-cron for this demo .

Create a folder for node cron project

mkdir my-node-corn

cd my-node-cron

npm init -y

Install Express using npm

npm install express

Install node-cron using npm

npm  install node-cron

Next, create an index.js file to setup the cron using express & node-cron & paste the below code.

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

/**
 * Creating a new express app
 */
app = express(); 

// Creating a cron job which runs on every second 
cron.schedule("* * * * * *", function() { 
    console.log("running a cron on every second"); 
}); 

const PORT = process.env.PORT || 3200;
app.listen(PORT, function () {
    console.log('app listening at port %s', PORT);
});

Now run the index.js file node index OR via nodemon & you will see the output in node console.

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
app listening at port 3200
running a cron on every second

That's it now write your cron logic inside cron.schedule() function.

Conclusion

This is a simple post about how to run cron jobs in nodeJs. I hope you like this article.

Related Articles