简体   繁体   English

Node.js:当服务器作为初始化启动时,如何运行特殊功能?

[英]Node.js : How to run a special function as server starts as a initialization?

I use Express framework, I have this function and I want to run it in intervals since server starts: 我使用Express框架,我具有此功能,并且自服务器启动以来我要定期运行它:

setTimeout(function () {
    console.log('timeout completed');
}, 1000);

so i put this piece of code to the initial file of Express.js Framework called App.js but it only runs twice, where is the problem and how could I fix it? 所以我将这段代码放到称为App.js的Express.js Framework的初始文件中,但是它只运行两次,问题出在哪里,我该如何解决?

The setTimeout function runs only once when that amount of time is completed, here in your case it is 1s(1000ms). 该时间量完成后, setTimeout函数运行一次 ,在您的情况下为1s(1000ms)。

Instead you may want to use setInterval which does the same thing except that it doesn't stop until you tell it so. 相反,您可能想使用setInterval ,它执行相同的操作,只是它直到您告知为止才停止。

Here is an example : 这是一个例子:

var max = 3;
var i = 0;

var timer = setInterval(function(){
   if(i === max){
      // stop the timer from looping.
      clearInterval(timer);
   }else{
      i++;
   }   
},1000);

Looks like you are describing a cron sort of job, why don't you use any of the many node crons modules instead. 看起来您正在描述一项cron作业,为什么不使用许多节点crons模块中的任何一个。

https://www.npmjs.com/package/node-cron https://www.npmjs.com/package/node-cron

Check that out, pretty straight forward. 检查一下,非常简单。

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

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