The Cron command-line utility is a job scheduler. So Cron do our same task that we are doing in daily life such as Sending emails, Notifications and other repetitive tasks.
Have you ever think that some of big tech company are doing backup on daily basis, So are they going to run script everyday?
So, the answer is Big No. They are using cron job So that write script once, then run everyday. We can even customize it in our need.
Prerequisites
- Check Node version v16.2.0 (or more).
If not installed then download from link else good to go...
Step 1 — Creating a Node Application and Installing Dependencies
Open terminal and run commands
mkdir CronJob
cd CronJob
Initialize npm package.json
npm init -y
Install dependancy
npm i node-cron
Step 2 — Crating task
So, here I want to make script to run ervery minutes.
create index.js by typing command in terminal(windows)
type Null > index.js
Open index.js
and add following code
var cron = require("node-cron");
cron.schedule("* * * * *", () => {
console.log("running a task every minute");
});
The syntax of * is base on Crontab
# ┌────────────── second (optional)
# │ ┌──────────── minute
# │ │ ┌────────── hour
# │ │ │ ┌──────── day of month
# │ │ │ │ ┌────── month
# │ │ │ │ │ ┌──── day of week
# │ │ │ │ │ │
# │ │ │ │ │ │
# * * * * * *
Here If we apply * for it will defaulty run every instance of time.
Ex.
- * * * * * * --> Every seconds. (Second is optinal)
- * * * * * --> Every minutes.
- 1 * * * * --> 1 min of every hours.
- 0 1 * * * --> 1 hours of every day.
- 0 0 3 * * --> Every Wednesday 00:00 run.
- 0 0 18 2 * --> Every 18,Feb day run.
Run Script
node index.js
After Every minutes, you will see results like:-
running a task every minute
running a task every minute
Examples
cron.schedule("0 0 18 2 *", function () {
console.log("---------------------");
console.log("Running Cron Job on 18 Feb");
// send people on their birthday.
sendEmail("myEmail@gmail.com", "Happy birthday");
});
Here, cron job run every 18-Feb day in every year. Once code run then send automatically send email to people on their birthday.
Conclusion
In this blog, we have discussed about Cron Job creation using Node JS and use in real-life and schedule your repetitive task and save your time...
Top comments (0)