javascript - NodeJs setInterval without extending process life time -
i simplified better understand need: task have is, have long unknown nodejs process (with lot of queued async functions never know when finished or that) , want have update process, store current process state in database. have start (it stores "start") , end process on top of process.on('beforeexit', function () { ... });. have handle "still in running" process requested our customer. want update state every ten minutes running timestamp (this function exists , called state.setrunningstate()
now have problem how can trigger function every ten minutes. going approach trigger on each event of working process function , compares if older 10 minutes ago. problem is: times there more time without event. second option setinterval() , here question about: if use setinterval nodejs process never reach end, process run endless until interval cleared. never know when should call clearinterval()
so question is: there way create such timeout without extending life time of nodejs process. if done should end , ignore rest of interval.
contrary of comments here, not strange requirement have executed periodically while process running without making process run infinitely make quite pointless.
there built-in mechanism that. if don't want interval (or timeout) stop process exiting need use .unref() method.
instead of:
setinterval(() => { console.log('interval'); }, 1000); use:
setinterval(() => { console.log('interval'); }, 1000).unref(); and interval not stop process exiting if there no other events pending.
try running example:
setinterval(() => { console.log('interval'); }, 1000).unref(); settimeout(() => { console.log('timeout 1'); }, 3000); settimeout(() => { console.log('timeout 2'); }, 5000); see docs:
Comments
Post a Comment