How to implement a cron job (using node-schedule) in a Node JS application

How to implement a cron job (using node-schedule) in a Node JS application

It has been a few days I have started learning Node JS.
My Node JS application has a get api which fetches the books information from the MongoDB database in json format when the http://localhost:portnumber/mybooks url is fired.
The book schema has four fields namely title, author, category and price.
Now, I want to introduce a cron job which will run every 10th and 50th minute of every hour. It will check if there is any book with price more than 100 (currency does not matter here), it will delete that record (or document) from the database. Means it will run at 7:10AM, 7:50AM , then in the next hour at 8:10AM and 8:50AM and so on.
I am starting my application with command ./bin/www from the application folder. However, I am not able to figure out how to implement this cron job service and where (in which file) to put this code so as to make it run at the above specified time whenever I start my application.
I am including the bits of code of my so-far developed application here to let you have a look. Currently it is working fine for the get rest api.
This is app.js:
var express = require(‘express’);
var path = require(‘path’);
var bodyParser = require(‘body-parser’);

Related:  Meteor: How should I update the Users collection to include a new attribute in the object / dictionary?

var index = require(‘./routes/index’);

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, ‘public’)));

app.use(‘/’, index);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error(‘Not Found’);
err.status = 404;

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error =‘env’) === ‘development’ ? err : {};

// render the error page
res.status(err.status || 500);

module.exports = app;

This is index.js :
var express = require(‘express’);
var router = express.Router();

var mongoose = require(‘mongoose’);
var Book1 = require(‘../models/mybook.model’);

var db = ‘mongodb://localhost/mybookdb’;
var mongoose = require(‘mongoose’);

var conn = mongoose.connection;

/* GET home page. */
router.get(‘/’, function(req, res, next) {
res.render(‘index’, { title: ‘Express’ });

router.get(‘/mybooks’, function(req, res) {
console.log(‘Showing all books’);
res.send(‘error has occured’);



module.exports = router;

and mybook.model as :
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;

var BookSchema = new Schema({

price: Number

module.exports = mongoose.model(‘Book’, BookSchema);

Related:  Mongo date range query using _id in PHP

Can anybody help me with how and in which file to implement the node-schedule cron to serve my requirement ?


Solution 1:

I could figure out how to do it. I got the idea from

Although it is not an exact solution but near. In this case the cron job runs continuously at every moment and the deletion is not implemented though. The cron scheduler code could be put in the index.js as follows :

var s =  require('node-schedule');    
var j = schedule.scheduleJob('* * * * *', function() {

Book1.find({price : {$gt:100}} , function(err, result) {    
   if(err) {
  else {
    if(!result) {
      console.log("No book found");
    } else {          
      console.log("Found a book with title "+result.title);

If anybody can complete this with the exact requirement would be helpful.Thanks.