Scheduling Jobs with node-cron... In Production Environment

Shameel Uddin - Jan 6 '23 - - Dev Community

Among other various packages in node.js for scheduling jobs, node-cron is one of the most widely used ones.

You can schedule things like creating backups, operations on filesystem like copying, deleting, etc. or sending E-mails and SMS on specific times with specific conditions.

The docs provide bare minimum usage of how it is supposed to be used.

In this blog, we will go through the usage of node-cron in production level environment with cleaner syntax and better readability.

For the sake of simplicity, we will be moving forward with a clean project.

Simply start the project with:

npm init
Enter fullscreen mode Exit fullscreen mode

Now install the package:

npm i node-cron
Enter fullscreen mode Exit fullscreen mode

You can use the boilerplate that I grabbed from MSDN docs for quickly setting up the environment.

Create index.js and copy the code provided below:

//Load HTTP module
const http = require("http");
const hostname = "127.0.0.1";
const port = 5000;

//Create HTTP server and listen on port 3000 for requests
const server = http.createServer((req, res) => {
  //Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");
});

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Enter fullscreen mode Exit fullscreen mode

Now you have set up the web server running at http://127.0.0.1:5000

Now create a proper architecture to store the code so that it's in better readable format.

Create file index.js in src/cron/ directory and paste the following code:

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

function cronJobs() {
  console.log("Initiating Cron Jobs...");
}

module.exports = cronJobs;

Enter fullscreen mode Exit fullscreen mode

Now call this function in your main index.js file in root directory.

At the top:

const cronJobs = require("./src/cron");
Enter fullscreen mode Exit fullscreen mode

In the main code before the server starts:

//Executing Cron Jobs
cronJobs();
Enter fullscreen mode Exit fullscreen mode

Your main index.js file should now look like this:

//Load HTTP module
const http = require("http");
const cronJobs = require("./src/cron");

const hostname = "127.0.0.1";
const port = 5000;

//Create HTTP server and listen on port 3000 for requests
const server = http.createServer((req, res) => {
  //Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World\n");
});

//Executing Cron Jobs
cronJobs();

//listen for request on port 3000, and as a callback function have the port listened on logged
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Enter fullscreen mode Exit fullscreen mode

Now when you run the server, you should see following debug log:

Initiating Cron Jobs...
Server running at http://127.0.0.1:5000/
Enter fullscreen mode Exit fullscreen mode

Now you are all set to schedule the jobs..

Create a directory called jobs in cron like this:

src/cron/jobs/
Enter fullscreen mode Exit fullscreen mode

Here you can store your functions for whatever purpose you are using this i.e., sending e-mails, creating backups, etc..

Create a new file index.js in src/cron/ folder and paste the following code:

const creatingBackup = () => {
  console.log("Backup ran at", Date.now());
};

module.exports = creatingBackup;
Enter fullscreen mode Exit fullscreen mode

It's a simple debug log but you can apply your implementation in the function.

Similary, you can use another one in src/cron/jobs/sendEmail.js as:

const sendEmail = () => {
  console.log("Email sent at", Date.now());
};

module.exports = sendEmail;

Enter fullscreen mode Exit fullscreen mode

Now make sure that both these functions are called src/cron/index.js

const cron = require("node-cron");
const creatingBackup = require("./jobs/creatingBackup");
const sendEmail = require("./jobs/sendEmail");

function cronJobs() {
  console.log("Initiating Cron Jobs...");
  cron.schedule("* * * * *", () => {
    creatingBackup();
  });

  cron.schedule("*/10 * * * * *", () => {
    sendEmail();
  });
}

module.exports = cronJobs;
Enter fullscreen mode Exit fullscreen mode

Note you can schedule tasks for any time of your choice, you just need to have a proper expression defined. These websites may help you in creating those:

You can find the code here at:
https://github.com/Shameel123/node-cron-production-way

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player