问题
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