简体   繁体   中英

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:

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?

The setTimeout function runs only once when that amount of time is completed, here in your case it is 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.

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.

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

Check that out, pretty straight forward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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