Building a Cron job can be extremely helpful when it comes to automating task at a fixed time, date, or intervals. For example, you can set a Cron job to run every Wednesday at 12pm that will execute an extract, load, and transfer program that will collect data from an endpoint, then take that data to push up to a database that you are working with. I’m going to show you how to build a simple Cron job using Node.js. There is also a video down below that you can also follow along with.
Getting Started
To begin creating a Cron job, you are going to need two packages. You will need to install node-cron and shelljs.
npm install node-cron
npm install shelljs
After installing the packages, it just takes a few lines to get the Cron job up and running.
The Code of a Cron Job
const cron = require("node-cron");let shell = require("shelljs");
cron.schedule("* * * * *", function(){
Cron will bring in the node-cron package and shell will bring in the shelljs package. Node-cron will allow to set up the schedule and shelljs will allow you to run commands within the shell. Cron.schedule takes 2 arguments, a string and a function. Taking this string “* * * * *” from left to right, minutes, hour, day of the month, month, and day of the week.
Minutes, hour, day of the month require an integer. 0 – 59 for minute and hour, 0 – 23 for hour, and 1 – 31 for day of the month. For month and day of the week, you can use 1 – 12 for month and 0 – 7 for day of the week. You can also use names instead of integers. Instead of 1, you can say Jan or January.
Inside of the cron.schedule function, this is where you can use the shelljs package.
if(shell.exec("dir").code !== 0){}};
You can also execute other scripts or software.
if(shell.exec("node otherNodeFile.js").code !== 0){}};
Shell.exec will execute the command it is given inside the current shell. It will also return a code that should not be 0 otherwise something went wrong.
That is all that is to getting a simple Cron Job up and running with Node.js.
For more tech-related content, visit jstroup.dev, or check out my YouTube channel for video tutorials!