Sails.js background processing loop, not related to connections

余生颓废 提交于 2019-12-23 03:51:30

问题


If you have a process loop you want to run continuously after delays with setTimeout (regardless of connections) where would that code go and be executed from?

It looks like the code would go in the services directory, but where do I start the loop? I tried in the app.js, but that doesn't work once sails is lifted it doesn't look like

Simple Example

// MyFoo.js
module.exports = {

    shouldFoo: true,

    doFoo: function(){
        if(this.shouldFoo){
            console.log('fooing ...');
            setTimeout(foo, 1000);
        } else {
            this.shutdownFoo();
        }
    },

    shutdownFoo: function(){
        // finish up process
    }
}

Then where do I put:

var fooer = require('./api/services/MyFoo.js');
fooer.doFoo();

回答1:


You can use bootstrap.js in config folder (http://sailsjs.org/#!documentation/config.bootstrap):

module.exports.bootstrap = function (cb) {
  var fooer = require('./api/services/MyFoo.js');
  fooer.doFoo();  

  // It's very important to trigger this callback method when you are finished 
  // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
  cb();
};



回答2:


Extending bredikhin ansnwer. You can add any function to bootstrap.js in config folder to start it with the server.

But you need to wait it to lift, before running if you need to use waterline db access.

module.exports.bootstrap = function(cb) {
sails.on('lifted', function(){
    //Process to calculate virtualTags and update on Tags Model
    VirtualTag.loopAnalytics();
});
 // It's very important to trigger this callback method when you are finished
 // with the bootstrap!  (otherwise your server will never lift, since it's waiting on the bootstrap)
cb();
};


来源:https://stackoverflow.com/questions/22608979/sails-js-background-processing-loop-not-related-to-connections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!