Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a Scheduled Job on Startup With Express

I'm just getting into Express and have ran into an issue. I have an app serving a REST API. That is all working fine. But I wanted to add a scheduled job using node-schedule (https://www.npmjs.com/package/node-schedule). I have implemented this module:

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

var scheduler = {
    scheduleJob: function(monitor) {
        var job = schedule.scheduleJob('* * * * *', function(){
            monitor.check();
        });
        return job;
    }
}

module.exports = scheduler;

In app.js I have added the following to the bottom since I found a single stack overflow question that was similar. This did not work for me:

app.on('listening', function () {
    console.log("App started, gathering monitors");
    var allMonitors = queries.getAllMonitorsInt();
    for (var i = 0; i < allMonitors.length; i++) {
        console.log("Monitor found: " + allMonitors[i].name);
        shdlr.scheduleJob(allMonitors[i]);
    }
});

I don't even get the "App started..." log message.

Am I doing this the right way or am I way off target?

like image 935
Twisty McGee Avatar asked Aug 31 '16 11:08

Twisty McGee


People also ask

How do I run a scheduled job?

You can start scheduled jobs immediately by using the Start-Job cmdlet , or by adding the RunNow parameter to your Register-ScheduledJob command. Job options set the conditions for running a scheduled job. Every scheduled job has one job options object.

Which service is used to run scheduled jobs?

A Cron is a time-based job scheduler. It enables our application to schedule a job to run automatically at a certain time or date. A Job (also known as a Task) is any module that you wish to run.

What is cron job in node?

Node-cron is a handy npm package which you can use to schedule jobs to run at specific times or intervals. It is most suitable for scheduling repetitive jobs such as email notifications, file downloads, and database backups.


1 Answers

The scheduler should be placed inside of app.listen callback, like this:

app.listen(3000, function () {
  console.log("App started, gathering monitors");
  var allMonitors = queries.getAllMonitorsInt();
  for (var i = 0; i < allMonitors.length; i++) {
      console.log("Monitor found: " + allMonitors[i].name);
      shdlr.scheduleJob(allMonitors[i]);
  }
});

Express doesn't support listening event, see an issue.

like image 165
G07cha Avatar answered Sep 17 '22 11:09

G07cha