Table of contents
Wake Up !!
Now, think for a moment if you suddenly missed your alarm for school or work or a meeting. I missed the last one yesterday 👀.
Okay, let's get back to our topic. When you are building web applications based on Node.js, you might need to run some sort of scheduled tasks like sending emails, system maintenance, or taking a daily backup of data (Hey, by the way, did you know, Whatsapp does this at 2 a.m. every day?). So, we will be creating a project to see how the scheduler works in our express application.
We are going to use an npm package node-cron which is made in pure JavaScript. This module allows us to schedule tasks in node.js applications. At least the documentation says this. Let's check it out.
Prerequisites
- Node.js (I am assuming that you have a basic knowledge about building an express server).
and that's it.
Note: Whatever the code snippets I will be sharing, follow it into your IDE for your practice. Make sure, you read the comments in the snippets. 😉
GitHub repo and Bonus are waiting for you at the end.
Step 0: Install the dependencies by running the following commands.
npm init -y
npm install --save express nodemon node-cron
Step 1: Setup a simple express server.
Cron scheduler method schedule() takes three arguments.
cron.schedule(cronExpression: string, task: Function, options: Object)
Now, there are various cronExpression depending upon at what time or at what instant we want to fire our task Function.
Allowed Values
Step 2: Add corn scheduler to your express server
Now, I will try to explain for every allowed value how our scheduler works. Focus on every logged statement.
cron.schedule("* * * * *",()=>{
console.log("It's a chole bhature time every minute");
})
cron.schedule("2,10 * * * *",()=>{
console.log("It's a tea time at 2nd and 10th minute");
})
cron.schedule("4-10 * * * *",()=>{
console.log("It's a coca cola time at every minute from 4th to 10th minute");
})
cron.schedule("*/3 * * * *",()=>{
console.log("Now, it's time for the medicine at every third minute");
// At 3rd, 6th, 9th mintutes...
})
cron.schedule("00 20 * * *",()=>{
console.log("It's my bed time at 08:00 p.m.");
})
cron.schedule("00 8 * * 1-5",()=>{
console.log("job is runnnig every weekday at 8 a.m.")
})
There are some scheduled task methods like start() & stop().
Stop(): The task won't be executed unless restarted.
Start(): It starts the scheduled task.
To see the magic of the above script, you have to start the server by the following command
node app.js stop start
Yay, we did it. Your cron scheduler is ready.
Bonus: Crontab Guru, Check it out
I hope this article helped you a bit. 😎✔
|| Article सम्पन्न ||