bluehost-banner
How to set up Cron job in Node.js

How to set up Cron job in Node.js

In this tutorial, we will learn how to setup cron job in NodeJS.

What is Cron Jobs?

 Let's say you are building web applications based on Node.js, and need to run some sort of scheduled tasks like sending emails, system maintenance, or taking a daily backup of data, this is where Cron Jobs comes in.

You can do the above things by setting up a Cron Job at that specific time.

So, here we will be creating a sample project to see how the scheduler works in our express application and can do this above tasks.

To do this we are going to use an npm package called node-cron which allows us to schedule tasks in node.js applications.

Prerequisites

  • Node.js (basic knowledge about building an express server).

Install the dependencies by running the following commands.

npm init -y
npm install --save express nodemon node-cron

 Setup a simple express server.

const express = require("express");
const app =express();

/....
.
.
.
...../
app.listen(4000,()=>console.log("Server started at port 4000"))

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.

Step 2: Add cron scheduler to your express server

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

cron.schedule('* * * * *', () => {
  console.log('this cron will run a task every minute');
});

Here we have some other cron scheduler examples:

cron.schedule("* * * * *",()=>{
    console.log("It will run every minute");
})

cron.schedule("2,10 * * * *",()=>{
    console.log("It will run on 3rd and 10th minute");
})

cron.schedule("5-11 * * * *",()=>{
    console.log("Every minute from 5th to 11th 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("At 08:00 p.m.");
})

cron.schedule("00 8 * * 1-5",()=>{
  console.log("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

our cron scheduler is ready.

You can also this tool to properly schedule tasks https://crontab.guru

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment