想用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);
大家有更好的吗?