How to Run Cron Jobs in Node.js ?
Last Updated :
17 Oct, 2024
Cron jobs are scheduled tasks that run at specific intervals in the background, commonly used for maintenance or repetitive tasks. 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:
To run the cron-jobs in Node.js we will be using the node-cron library. Install and import it into your project. You then define a cron expression that determines the task's schedule and use cron.schedule() to execute functions at specified intervals.
Syntax:
cron.schedule("* * * * *", function() {
// Task to do
});
Steps to Create Node App
Step 1: Go to the project directory and run this command in the terminal
npm init -y
Step 2: Install the required Modules
npm install express node-cron
The updated dependencies in the package.json are:
"dependencies": {
"express": "^4.18.2",
"node-cron": "^3.0.0"
}
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:
JavaScript
// 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);
Run the file using command
node index
, you will see the output like below:

Writing to a log file
ron jobs can be used to schedule logging tasks in a system. We can log server status for a given time for monitoring purposes.
Example: This example sets up a cron job using node-cron to log a status message to logs.txt every 10 seconds.
JavaScript
// index.js
// Importing required packages
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
app = express();
// Setting a cron job
cron.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: This example uses node-cron to send an email every minute with Nodemailer, automatically triggering the sendMail() function.
JavaScript
// index.js
// Importing packages
const cron = require("node-cron");
const express = require("express");
const nodemailer = require("nodemailer");
app = express();
// Calling sendEmail() function every 1 minute
cron.schedule("*/1 * * * *", function() {
sendMail();
});
// Send Mail function using Nodemailer
function 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:
Similar Reads
How to Run Java Code in Node.js ?
Running Java code within a Node.js environment can be useful for integrating Java-based libraries or leveraging Java's robust capabilities within a JavaScript application. This article will guide you through the steps required to execute Java code from a Node.js application, covering various methods
2 min read
How to Run C Code in NodeJS?
Developers can take advantage of Node.js's robust ecosystem and performance by running C code within the framework. Child processes, Node.js extensions, and the Foreign Function Interface (FFI) can all assist in this. There is flexibility to integrate C code based on particular requirements, as each
3 min read
How to Copy a File in Node.js?
Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
2 min read
How to Install Node.js on Linux
Installing Node.js on a Linux-based operating system can vary slightly depending on your distribution. This guide will walk you through various methods to install Node.js and npm (Node Package Manager) on Linux, whether using Ubuntu, Debian, or other distributions.PrerequisitesA Linux System: such a
6 min read
How to Take Input in Node.js ?
Taking input in a Node.js application is essential for building interactive command-line interfaces, processing user input, and creating dynamic applications. Node.js provides several methods for receiving input from users, including reading from standard input (stdin), command-line arguments, and u
2 min read
How to handle Child Threads in Node.js ?
Node.js is a single-threaded language and uses the multiple threads in the background for certain tasks as I/O calls but it does not expose child threads to the developer.But node.js gives us ways to work around if we really need to do some work parallelly to our main single thread process.Child Pro
2 min read
How to Create API to View Logs in Node.js ?
Log files are essential for monitoring and troubleshooting applications. They provide insight into the applicationâs behaviour and help identify issues. In a Node.js application, you might want to create an API that allows you to view these logs easily. This can be particularly useful for centralize
5 min read
How to refresh a file in Node.js ?
Node.js has seen an important growth in past years and is still increasing its value in many organizations and business models. Companies like Walmart or PayPal have already started to adopt it. NPM, the package manager of Node.js has been already installed when you install Node.js and is ready to r
2 min read
How to Install NodeJS on MacOS
Node.js is a popular JavaScript runtime used for building server-side applications. Itâs cross-platform and works seamlessly on macOS, Windows, and Linux systems. In this article, we'll guide you through the process of installing Node.js on your macOS system.What is Node.jsNode.js is an open-source,
6 min read
How to Open Node.js Command Prompt ?
Node.js enables the execution of JavaScript code outside a web browser. It is not a framework or a programming language, but rather a backend JavaScript runtime environment that allows scripts to be executed outside the browser. You can download Node.js from the web by visiting the link "Download No
2 min read