How to run Cron Jobs in Node.js

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. 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
It is usually used for system admin jobs such as backups, logging, sending newsletters, subscription emails and more.
Syntax:

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

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)

Example: Create a new file named index.js and add the following 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);

Leave a comment

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