简体   繁体   中英

callback in node-schedule's callback

In my (express.js based) loopback app I want to schedule a task to run every 1 second. It should count every open ticket, and if they already open for a certain time, then an email should be sent. Below is a simplified code.

The problem, that 'scheduleJob' is logged, as expected, but the number of tickets is not. I think it is a context problem. How should I log the number of the found ticket? How should I communicate back from count 's callback to the schedule 's callback?

var schedule = require('node-schedule');
module.exports = function(app) {
  var Ticket = app.models['Ticket']

  var j = schedule.scheduleJob('* * * * * *', function(){
    console.log('scheduleJob')
    Ticket.count(function(err, count){
      if (err) {console.log(err)}
      console.log(count)
    })
  });
};

Do not count all the open ticket like that - It costs a lots of resources.

You should keep the number of ticket in your node.js and increase/decrease it. If you have multiple processes interacting with the database, makes one of them your master and make it handle this task.


About your problem, it seems that the library node-schedule do not support asynchronous calls.



Algorithm

At your program start, look up at the ticket in your database and retrieve the next timestamp when you should send an email.

Example, you want to send an email if a ticket is open for 1 hour, and your database have :

ticket 1 / 10 min
ticket 2 / 40 min

So your next mail should be sent in 20 min (60 min - 40 min).

use setTimeout() to wake up your node in 20 min. When you wake up, send the mail, and look at your database again for the next mail to send.

Recalcul your setTimeout if there is a new Ticket inserted in your database or If one get removed/updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM