Implementing Job Schedulers in Node.js
Tags: showdev, webdev, tutorial, beginners
Published: 2019-09-20 21:30:06

---
title: Implementing Job Schedulers in Node.js
published: true
description: Implementing Job Schedulers in Node.js
tags: showdev,webdev,tutorial,beginners
canonical_url : https://cloudnweb.dev/2019/09/implementing-job-schedulers-in-node-js/
---
<!-- wp:paragraph -->
<p>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</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A Recent article on Nodejs,</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/09/pm2-for-node-js-developers/"> PM2 for Node.js developers </a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/09/building-p2p-video-chat-application-using-webrtc-and-node-js/"> Building P2P Video Chat Application using webRTC and Node.js </a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://cloudnweb.dev/2019/08/understanding-eventemitter-in-node-js-with-a-usecase/"> Understanding EventEmitter in Node.js With a UseCase </a></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Ever wondered how the application server back up the files periodically without any physical interruption. This is where Cron jobs come in.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Cron Jobs schedules a job periodically to do the actions that are configured to do.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>there are few use cases where cron jobs play a vital role. they are,</p>
<!-- /wp:paragraph -->

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

<!-- wp:heading {"level":3} -->
<h3>How cron job works</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>we will write a cron job to archive the old records in the database in a production application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Firstly, create a project and install the following dependencies,</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>npm init --yes
npm install express node-cron mongoose faker</code></pre>
<!-- /wp:code -->

<!-- wp:list -->
<ul><li><strong>express </strong>- web server library in nodejs</li><li><strong>node-cron</strong> - cron job scheduler library in nodejs</li><li><strong>mongoose </strong>- ORM for MongoDB</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>After that, create a file called <strong>Model.js</strong> and add the following code</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><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)</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Mainly, <strong>Model.js</strong> creates a mongoose schema for a DB table which stores the weather data in the database.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After that, create a file called<strong> scheduler.js</strong> and add the code for job scheduler.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>cron.schedule("* * * * * *",() => {
    console.log("Running every minute");
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>cron schedule schedules the job for time format that is mentioned. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":1364} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/09/nodeschduler.png" alt="" class="wp-image-1364"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>To learn more about cron job format, there is a great site <a href="https://crontab.guru/">crontab-guru</a> which explains in detail</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Connect the mongoose with the Express to insert some dummy data to database.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>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 &lt; 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);
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>To insert some dummy data using <a href="https://github.com/marak/Faker.js/">fakerjs</a>. run the script with the command, and visit the URL <a href="http://localhost:4000/insertdata ">http://localhost:4000/insertdata </a></p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>node scheduler.js</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>it will create some bulk dummy data to test the job scheduler. Now it is time to add the job scheduler.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>cron.schedule("* * * * */3 *",async() => {

    var d = new Date();
    d.setMonth(d.getMonth() - 2); //1 month ago
    
    await model.archiveData(d);

    console.log("scheduler => archived");  
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Above cron job will run every 3 months, to mark the data as archived in the database.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Likewise, we can use cron jobs to schedule a job for our application logics.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Summary</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>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.  </p>

<p>If you want to implement job scheduler in a production level standard with minimal effort, I recommend you to check out <a href="https://github.com/breejs/bree">bree</a></p>

<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Reference :  <a href="https://crontab.guru/">https://crontab.guru</a> </p>
<!-- /wp:paragraph -->

<!-- wp:html -->
<a href="https://click.linksynergy.com/link?id=YIJ5oggSvpI&offerid=507388.1587718&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fadvanced-node-for-developers%2F"><IMG border=0 src="https://i.udemycdn.com/course/480x270/1587718_8fdf.jpg" ></a><IMG border=0 width=1 height=1 src="https://ad.linksynergy.com/fs-bin/show?id=YIJ5oggSvpI&bids=507388.1587718&type=2&subid=0" >
<!-- /wp:html -->