Build a Job Schedulers in Node.js

Build a Job Schedulers in Node.js

In this article, we will see what are job schedulers and how to implement the job schedulers in nodejs. Implementing Job Schedulers in Node.js

Ever wondered how the application server back up the files periodically without any physical interruption. This is where Cron jobs come in.

Cron Jobs schedules a job periodically to do the actions that are configured to do.

there are few use cases where cron jobs play a vital role. they are,

  • Deleting Log files - Application generates a lot of logs.clearing old logs will save lots of space in the server. it can be done using cron jobs.
  • DB Backup - Database backup saves the application from disasters. Cron job will be helpful to do that.
  • Application Logic - we can use cron jobs to do some application logic on a time basis.

How cron job works

we will write a cron job to archive the old records in the database in a production application.

Firstly, create a project and install the following dependencies,

npm init --yes
npm install express node-cron mongoose faker
  • express - web server library in nodejs
  • node-cron - cron job scheduler library in nodejs
  • mongoose - ORM for MongoDB

After that, create a file called Model.js and add the following code

const mongoose = require("mongoose")
const weatherSchema = new mongoose.Schema({
  minTemp: {
    type: Number,
  },
  maxTemp: {
    type: Number,
  },
  recordedDate: {
    type: Date,
  },
  isArchived: {
    type: Boolean,
    default: false,
  },
})
class Weather {
  static getRec(date) {
    return this.find({
      recordedDate: {
        $lte: new Date(date),
      },
    }).exec()
  }
  static insertBulkData(data) {
    return this.insertMany(data)
  }
  static archiveData(date) {
    return this.updateMany(
      {
        recordedDate: {
          $lte: new Date(date),
        },
      },
      {
        $set: {
          isArchived: true,
        },
      }
    ).exec()
  }
  static getArchivedData() {
    return this.find({
      isArchived: true,
    }).exec()
  }
}
weatherSchema.loadClass(Weather)
module.exports = mongoose.model("Weather", weatherSchema)

Mainly, Model.js creates a mongoose schema for a DB table which stores the weather data in the database.

After that, create a file called scheduler.js and add the code for job scheduler.

cron.schedule("* * * * * *", () => {
  console.log("Running every minute")
})

cron schedule schedules the job for time format that is mentioned.

nodeschduler

To learn more about cron job format, there is a great site crontab-guru which explains in detail

Connect the mongoose with the Express to insert some dummy data to database.

const cron = require("node-cron")
const express = require("express")
const mongoose = require("mongoose")
const app = express()
const faker = require("faker")
const model = require("./Model")
mongoose
  .connect("mongodb://localhost:27017/nodescheduler")
  .then(res => {
    console.log("mongoose connected successfully")
    app.get("/insertdata", async (req, res) => {
      let data = []
      for (let i = 0; i < 100; i++) {
        let record = {
          minTemp: faker.random.number(),
          maxTemp: faker.random.number(),
          recordedDate: faker.date.past(),
        }
        data.push(record)
      }
      await model.insertBulkData(data)
      res.send("Data is inserted")
    })
    app.listen(4000, () => {
      console.log("Server is running port 4000")
    })
  })
  .catch(err => {
    console.error(err)
  })

To insert some dummy data using fakerjs. run the script with the command, and visit the URL http://localhost:4000/insertdata

node scheduler.js

it will create some bulk dummy data to test the job scheduler. Now it is time to add the job scheduler.

cron.schedule("* * * * */3 *", async () => {
  var d = new Date()
  d.setMonth(d.getMonth() - 2) //1 month ago
  await model.archiveData(d)
  console.log("scheduler => archived")
})

Above cron job will run every 3 months, to mark the data as archived in the database.

Likewise, we can use cron jobs to schedule a job for our application logics.

Summary

Above all, cron jobs play a vital role in some application development use cases. it is always good to know how cron jobs work in application development.

node-js web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.