Create and Run Scheduled Jobs with Node.js
Ever wanted to do specific things on your application server at certain times without having to manually run them yourself? This is where scheduled tasks come in handy.
In this article, we’ll look at how to create and use Cron jobs in Node applications. To do this, we’ll make a simple application that automatically send email from the server. Another advantage of Cron jobs is that you can schedule the execution of different scripts at different intervals from your application.
GitHub: Checkout the complete code here
Getting Started
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 cron-job
cd cron-job
npm init
touch index.js
Install the following dependencies.
npm i express node-cron nodemailer
express
- powers the webserver
node-cron
- task scheduler in pure JavaScript for node.js
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();
const port = 3000
......
......app.listen(port, () =>
console.log(`Server running at http://localhost:${port}`));
To see how this module works, add the following to your index.js
file which displays a message every minute:
// schedule tasks to be run on the server
cron.schedule("* * * * *", function() {
console.log("Running a task every minute");
});
Now, when you run the server, we get the following result:
Output
Server running at http://localhost: 3000Running a task every minute
Running a task every minute
You have a task running every minute. Stop the server with CTRL+C
.
Once that is done, update the index.js
file to add a section that defines the mailer and sets the username and password for a Gmail account:
const cron = require('node-cron');
const express = require('express');
let nodemailer = require("nodemailer");app = express();
const port = 3000;// create mail transporter
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'your_email@gmail.com',
pass: 'your_password'
}
});
Warning: You will need to temporarily allow non-secure sign-in for your Gmail account if you’d like to use it for testing purposes here. For production applications, configure a specific secure Email account and use those credentials.
Then add the task to send the messages every minute:
cron.schedule("* 01 * * *", function () {
console.log("Runnig a task every minute"); let mailOptions = {
from: "support@gmail.com",
to: "any_user_mail@gmail.com",
subject: `Cron job`,
text: `Hi there, this email was automatically sent by node cron`
};transporter.sendMail(mailOptions, function (error, info) {
if (error) {
throw error;
} else {
console.log("Email successfully sent by cron!");
}
});
});app.listen(port, () =>
console.log(`Example app listening at http://localhost:${port}`)
);
Now, when you run the server using the command node index.js
, you get the following result:
CONCLUSION
In this article, you used node-cron
to schedule jobs in your Node.js applications.
If you came thus far congrats, ✌.
Surely, you’ve got questions or issues as you went through this tutorial, kindly drop your comments and you’d be responded to ASAP.
Once again thanks for reading, Clap, and share!👌
GitHub: Checkout the complete code here