DEV Community

Akhil Dhiman
Akhil Dhiman

Posted on

Scheduling Cron Jobs in Node.js

Cron jobs in node.js come in handy whenever there's a need to run scripts on the server over and over again at certain intervals. It could be any task, such as sending email to the user at any particular time or day. In this article, we're going to test that with the help of nodemailer.

To begin with, we will create a node application with the following commands:

mkdir cron-jobs
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now, we need to install node-cron and nodemailer packages from npm. Create a file called index.js as the entry point of the application or simply, our server file.

npm install node-cron 
npm install nodemailer
touch index.js
Enter fullscreen mode Exit fullscreen mode
//index.js
const express = require("express")
const cron = require("node-cron")
const nodemailer = require("nodemailer")
const app = express()

app.listen(8000)
Enter fullscreen mode Exit fullscreen mode

Before setting up the cron job, let's first configure nodemailer.

let transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: "email@gmail.com",
        pass: "password"
    }
})

let mailOptions = {
    from: "email@gmail.com",
    to: "receiveremail@gmail.com",
    subject: "Nodemailer",
    text: "Testing Nodemailer",
    html: "<h1>Testing Nodemailer</h1>"
}

transporter.sendMail(mailOptions, (err, info) => {
    if(err) {
        console.log("error occurred", err)
    } else {
        console.log("email sent", info)
    }
})
Enter fullscreen mode Exit fullscreen mode
  • transporter is an object that holds the email service we are using, an auth object having sender's email and password.
  • mailOptions contains standard email info. We can also use templates such as ejs or hbs.
  • sendMail method takes in mailOptions and a callback.

It's important to note that we're using gmail as the service. In order to use it, we will have to turn on the less secure app feature.

Cron's schedule method takes in:

  • Time interval at which the cron job will run.
  • Callback function which runs after the message is sent.

The asterisks in cron.schedule refer to the time interval at which the code will get executed. We can set the time up as described in the format below:

┌──────────────── second (optional) 
| ┌────────────── minute 
| | ┌──────────── hour 
| | | ┌────────── day of month 
| | | | ┌──────── month 
| | | | | ┌────── day of week
| | | | | | 
| | | | | |
* * * * * *
Enter fullscreen mode Exit fullscreen mode
//For a cron job to run every second
cron.schedule("* * * * * *", () => {
    //code to be executed
})

//This will run every 10 seconds
cron.schedule("*/10 * * * * *", () => {
    //code to be executed
})

//This will run at the start of every minute
cron.schedule("0 * * * * *", () => {
    //code to be executed
})

//This will run at the start of every hour
cron.schedule("0 * * * *", () => {
    //code to be executed
})

// This will run on 20th of every month at 02:00 hours
cron.schedule("* 02 20 * *", () => {
    //code to be executed
})
Enter fullscreen mode Exit fullscreen mode

Setting up the cron job with nodemailer

Final code would look like this:


const express = require("express")
const cron = require("node-cron")
const nodemailer = require("nodemailer")
const app = express()

let transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
        user: "email@gmail.com",
        pass: "password"
    }
})

// Here, we're scheduling a cron job and it will send an email at the start of every minute.
// Info contains the mail content.
// In case of sending mail to multiple users, we can add multiple recipients.
cron.schedule("* * * * *", () => {
    console.log("sending email")
    let mailOptions = {
        from: "email@gmail.com",
        to: "receiveremail@gmail.com",
        subject: "Nodemailer",
        text: "Testing Nodemailer",
        html: "<h1>Testing Nodemailer</h1>"
}

transporter.sendMail(mailOptions, (err, info) => {
    if (err) {
        console.log("error occurred", err)
    } else {
        console.log("email sent", info)
    }
  })
})

app.listen(8000)

Enter fullscreen mode Exit fullscreen mode

Finally, head over to your terminal and start the server.

node index.js
Enter fullscreen mode Exit fullscreen mode

Thank You for reading this article. Follow me on Twitter for more updates.

Top comments (4)

Collapse
 
ashoutinthevoid profile image
Full Name

What purpose is express meant to serve in this example?

You can use nodemailer and node-cron to send an email each minute without involving express at all.

You could also use nodemailer alone and use the systems native cron to launch the node process periodically - perhaps you can expand the article to offer an example of when/why node-cron is more useful?

Collapse
 
kishan_bharda profile image
Kishan Bharda

How to store cron references in the database to stop after some time? For example, let users have scheduled push notification and after some time user want to can the notification so How I can stop the scheduled cron?

Collapse
 
banzyme2 profile image
ENDEESA

What happens if the server is down for some time?

Collapse
 
akhildhiman profile image
Akhil Dhiman

No job will run when the server is down or gets crashed. The server needs to be up and running in order to execute scheduled tasks.