Cron job creation using Node JS.

Meshv Patel - Nov 4 '22 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode
cd CronJob
Enter fullscreen mode Exit fullscreen mode

Initialize npm package.json

npm init -y
Enter fullscreen mode Exit fullscreen mode

Install dependancy

npm i node-cron
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Open index.js and add following code

var cron = require("node-cron");

cron.schedule("* * * * *", () => {
  console.log("running a task every minute");
});
Enter fullscreen mode Exit fullscreen mode

The syntax of * is base on Crontab

 # ┌────────────── second (optional)
 #  ┌──────────── minute
 #   ┌────────── hour
 #    ┌──────── day of month
 #     ┌────── month
 #      ┌──── day of week
 #      
 #      
 # * * * * * *
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Run Script

  node index.js
Enter fullscreen mode Exit fullscreen mode

After Every minutes, you will see results like:-

running a task every minute
running a task every minute
Enter fullscreen mode Exit fullscreen mode

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");
});
Enter fullscreen mode Exit fullscreen mode

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...

. . .