In this tutorial, I will show you how to schedule cron jobs in node js. Cron jobs are generally repetitive tasks that have to be run by the operating system. Examples of such tasks would be sending emails, taking backups, storing logs, etc. Here we'll be using a package called node-cron that lets us easily schedule and manage jobs in the node js.
npm i node-cron
touch jobs.js
Here is the basic syntax of the single job
const cron = require("node-cron");
cron.schedule("* * * * *", function() {
console.log("Print this every minute")
});
Here is the description of time formatting
┌──────────────── second (optional) (Valid range 0-59)
| ┌────────────── minute (Valid range: 0-59)
| | ┌──────────── hour (valid range: 0-23)
| | | ┌────────── day of the month (Valid range: 1-31)
| | | | ┌──────── month (Valid range: 1-12)
| | | | | ┌────── day of the week (valid range: 0-7)
| | | | | |
| | | | | |
* * * * * *
Run every 5 seconds
cron.schedule("*/5 * * * * *", function() {
console.log("Run every 5 seconds")
});
Run every minute
cron.schedule("* * * * *", function() {
console.log("Run every minute")
});
Run every hour between 10-20 minutes
cron.schedule('10-20 * * * *', () => {
// code
});
Run february and march every sunday
cron.schedule('* * * Feb,March Sun', () => {
// Run code
});
Run 8 AM every monday
cron.schedule('0 8 * * 1', () => {
// Run code
});
You can also manually start and stop the jobs via respective methods of the task.
const cron = require("node-cron");
let job = cron.schedule('* * * * *', () => {
console.log('Hello world');
}, {
scheduled: false
});
job.start()
console.log("Stopping the job")
job.stop()
You can also destroy the job forever
job.destroy()
If you don't want to use any package such as node-cron then other options for you would be to use the builtin set timeout function. But the only drawback is that you won't get any time control and accuracy for your tasks. Here is the code example.
const task = (counter)=>{
console.log("Running every five seconds")
console.log("Counter:", counter)
counter++
setTimeout(task, 5000, counter)
}
task(0)