简体   繁体   English

如何防止节点程序停止运行?

[英]How can I prevent node program from stop running?

I see many applications that uses node runs forever. 我看到许多使用节点的应用程序永远运行。

Therefore, I tried using setInterval method, which I assumed it will let it run forever, but apparently it doesn't. 因此,我尝试使用setInterval方法,该方法假定它可以使其永远运行,但显然不会。

var request = require('request');

var queue = function(item) {
  request({
    uri: 'http://www.google.net'
  },
  function(error, response, body) {
    if (!error && response.statusCode == 200) {
      console.log(body) // Print the google web page.
    }
  })
};
setInterval(queue("google"),1000); //do this every 1 second.

When I run above program, it stops after a second. 当我运行上面的程序时,它在一秒钟后停止。

How can I can modify above codes to keep it running if I run it with node? 如果使用node运行它,如何修改上面的代码以使其运行?

Actually you have a bug in your code: 实际上,您的代码中存在一个错误:

setInterval(queue("google"),1000); //do this every 1 second.

Instead of passing a function above as the first parameter, you are passing the result of executing a function. 而不是将上面的函数作为第一个参数传递,而是传递了执行函数的结果。

So either do setInterval(queue, 1000) or do the following if you want multiple params: 因此setInterval(queue, 1000)如果需要多个参数setInterval(queue, 1000)请执行setInterval(queue, 1000)或执行以下操作:

setInterval(function() {
  queue(how_many_params_you_want);
}, 1000);

更好的解决方案是使用npm: 永远

You have to assign setInterval to a local variable. 您必须将setInterval分配给局部变量。

setInterval(function(){},1000);

will stop. 会停止。

var timer = setInterval(function(){},1000);

will not. 将不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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