How to Schedule Cron Jobs in Node.js
By: Swathi Prasad
Tags: Nodejs, Backend Development, JavaScript, Software Engineering, Node

Many applications need to run some sort of scheduled tasks for chores like system maintenance, administration, taking a daily backup of data or sending emails. A Cron is a time-based job scheduler, which enables applications to schedule a job to run automatically at a certain date or time.

Node.js

There are various open source tools available for scheduling cron jobs in Node.js. In this article, we will look at a simple example using a module called node-cron.

Installing Dependencies

In this article, we would be creating a cron job to send emails. Create a simple Node.js project by running the following command in a terminal or bash.

mkdir node-cron-job-scheduler cd node-cron-job-scheduler npm init -y touch index.js

Install the following dependencies.

npm install — save express node-cron nodemailer

In index.js file, import the above dependencies.

const cron = require(“node-cron”); const express = require(“express”); const nodeMailer = require(‘nodemailer’);

We will now create a simple Node server by adding:

app = express(); … app.listen(8000);

Creating a Test Email Account

Before we create a cron job, let’s create a test email account at https://ethereal.email/. We will use these test credentials to send an email. We can also create test user account using nodemailer module as follows:

let testAccount = nodemailer.createTestAccount();

testAccount.user and testAccount.pass can be used for providing credentials to Mail transporter object.

Scheduling Cron Job

Let us create a cron job using node-cron module.

cron.schedule(“* * * * *”, function () { console.log(“Running Cron Job”); });

Here, the cron job runs for every minute. Start the Node.js server and you will see the message “Running Cron Job” in the console at every minute. We can schedule jobs at different days or time.

For example: “* * 5 * *“ => This represents 5th of every month. “30 7 * * *” represents every day at 7th hour and 30th minute.

Let’s add the logic to send email using nodemailer module within the cron job.

let transporter = nodeMailer.createTransport({ host: ‘smtp.ethereal.email’, port: 587, secure: false, // true for 465, false for other ports auth: { user: ‘<TEST_USER>’, // generated ethereal user pass: ‘<TEST_PASSWORD>’ // generated ethereal password } }); const mailOptions = { from: ‘“John Doe” <john.doe@example.com>’, // sender address to: ‘jane.doe@example.com’, // list of receivers subject: ‘Hello there!’, // Subject line text: ‘A Message from Node Cron App’, // plain text body html: ‘<b>A Message from Node Cron App</b>’ // html body }; transporter.sendMail(mailOptions, function (error, info) { console.log(info.messageId); if (err) { console.log(err); } });

Here, we have created a transporter object using nodemailer module and we have used Ethereal as the SMTP server. Provide the test account credentials that we created earlier.

In the mailOptions object, we have provided all the necessary information to construct an email.

Testing the Cron Job

Run the server using the command node index.js . We will see the message Id in the console at every minute as follows:

Running Cron Job

<bd7dd14e-3e9b-e495–12d5-c5e67a11af5c@example.com>

In Ethereal site, we can see the emails that were sent from the server using the button shown in the screenshot below.

Ethereal website

Test Mails on Ethereal site

We can use any real SMTP server of our choice to send emails.

The example for this article is available on GitHub repository.