想用node一个守护进程的demo。目前看到的代码不是web服务就是net服务,都是依靠系统提供的listen接口来实现程序的持久执行的。
不借助http、net模块,如何写出一个event loop呢?
我能给出的方案是:
function Worker()
{
this.MaxIterations = 1000000;
this.Enabled = true;
this.condition = true;
this.iteration = 0;
this.Loop = function()
{
if (this.condition
&& this.Enabled
&& this.iteration++ < this.MaxIterations)
{
console.log(this.iteration);
setTimeout(this.Loop.bind(this),0);
}
};
this.Stop = function()
{
this.Enabled = false;
};
}
var w = new Worker();
setTimeout(w.Loop.bind(w), 0);
setTimeout(w.Stop.bind(w), 3000);
大家有更好的吗?
8 回复
function start(){ console.log(‘Mother process is running.’);
var ls = require('child_process').spawn('node', ['app.js']);
ls.stdout.on('data', function (data)
{
console.log(data.toString());
});
ls.stderr.on('data', function (data)
{
console.log(data.toString());
});
ls.on('exit', function (code)
{
console.log('child process exited with code ' + code);
delete(ls);
ls = null;
setTimeout(start,3000);
});
}