By Chris Nwamba
Translation: Crazy geek
Original text: pausing. IO/tutorials/n…
Reproduced without permission
I used to want to perform certain actions at certain times without having to run them myself.
In this article, we’ll explore how to create and use Cron jobs in Node programs. To do this, we will create a simple program that will automatically remove the automatically generated error.log file from the server. Another advantage of Cron jobs is that you can schedule programs to execute different scripts at different intervals.
The premise condition
To continue with this tutorial, you need the following:
- Node installed on your machine
- You have NPM installed on your computer
- JavaScript basics
An introduction to
First, the following command creates a new Node program for the project and then initializes it:
mkdir cron-jobs-node cd cron-jobs-node
npm init -y
Copy the code
Installing a Node Module
In order for the program to work properly, we will need several dependencies. You can install them by running the following command:
npm install express node-cron fs
Copy the code
Express-web server
Node-cron – A pure JavaScript task planner for Node.js
Fs – File system module
Build the back-end server
Create an index.js file and import the necessary Node modules:
touch index.js
Copy the code
Edit the index.js file as follows:
// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs"); app = express(); [...].Copy the code
This is the entrance to Node-cron. We want to be able to delete error log files periodically without having to do this manually. We’ll do this with Node-cron. Let’s start with a simple task. Add the following to your index.js file:
// index.js[...].// schedule tasks to be run on the server
cron.schedule("* * * * *".function() {
console.log("running a task every minute");
});
app.listen(3128); [...].Copy the code
Now we get the following result when we run the server:
> node index.js
running a task every minute
running a task every minute
Copy the code
Time interval for scheduling tasks
With Node-cron, you can schedule tasks at different intervals. Let’s look at how you can use different time intervals to schedule tasks. In the example above, we created a simple Cron job, passing the parameter * * * * * to the.schedule() function. These parameters have different meanings when used:
* * * * * *
| | | | | |
| | | | | day of week
| | | | month
| | | day of month
| | hour
| minute
second ( optional )
Copy the code
In this example, if you wanted to delete log files from the server on the 21st of each month, you could update index.js to look like this:
// index.js
const cron = require("node-cron");
const express = require("express");
const fs = require("fs");
app = express();
// schedule tasks to be run on the server
cron.schedule("* * 21 * *".function() {
console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
console.log("Running Cron Job");
fs.unlink("./error.log", err => {
if (err) throw err;
console.log("Error file succesfully deleted");
});
});
app.listen("3128");
Copy the code
When the service runs, you get the following output:
Note: To simulate this task, you can set the interval to a shorter time by setting the number of minutes in the parameter
You can do anything in the scheduler. Everything from creating files to sending e-mails and running scripts. Let’s look at some more use cases
Use case 2 – Backing up the database
Ensuring the accessibility of user data is critical for any enterprise. In the event that your database is damaged by an accident, if you do not have a backup, everything will become a mess. To avoid this, you can also use Cron jobs to periodically back up existing data in your database. Let’s look at how to do this.
For illustration purposes, we will use the SQLite database
First, we need to install a Node module that allows us to run shell scripts:
npm install shelljs
Copy the code
Also install SQLite:
npm install sqlite3
Copy the code
Now create the sample database by running the following command:
sqlite3 database.sqlite
Copy the code
To back up your database every night at 11:59 PM, update your index.js file as shown below:
// index.js
const fs = require("fs");
let shell = require("shelljs");
const express = require("express");
app = express();
// To backup a database
cron.schedule("59 23 * * *".function() {
console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
console.log("Running Cron Job");
if (shell.exec("sqlite3 database.sqlite .dump > data_dump.sql").code ! = =0) {
shell.exit(1);
}
else{
shell.echo("Database backup complete"); }}); app.listen("3128");
Copy the code
Now when you run the service with the following command:
node index.js
Copy the code
You get the following results:
Use Case 3 – Send E-mail once in a while
You can also use Cron jobs to send emails at different intervals to keep your users up to date with the business. For example, you could curate a list of interesting links and send them to users every Sunday. To do this, you need to do the following.
Install nodemailer by running the following command:
npm install nodemailer
Copy the code
When done, update the index.js file as follows:
// index.js
const cron = require("node-cron");
const express = require("express");
let nodemailer = require("nodemailer");
app = express();
// create mail transporter
let transporter = nodemailer.createTransport({
service: "gmail".auth: {
user: "[email protected]".pass: "userpass"}});// sending emails at periodic intervals
cron.schedule("* * * * Wednesday".function(){
console.log("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");
console.log("Running Cron Job");
let mailOptions = {
from: "[email protected]".to: "[email protected]".subject: `Not a GDPR update ;) `.text: `Hi there, this email was automatically sent by us`
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
throw error;
} else {
console.log("Email successfully sent!"); }}); }); app.listen("3128");
Copy the code
Note: For testing purposes, you’ll need to temporarily allow your Gmail account to log in unsecurely.
Now, when you run the service with Node index.js, you get the following result:
conclusion
In this article, I’ve shown you Cron jobs and how to use them in Node.js programs. Here’s the source link on GitHub.