Reputation: 1393
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?
Upvotes: 7
Views: 5499
Reputation: 4154
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.
Upvotes: 6