首页 > 解决方案 > nodejs es6 way of running task every second for 10 seconds

问题描述

I am trying to come up with an elegant implementation for an async function that attempts a check operation check() every t seconds for a maximum n number of times; i.e. I would like to immediately return if check() === true, otherwise I would like to bail out after t * n seconds (n attempts).

I have a working implementation using counter-based for-loop and simple delay:

// doc and pair are defined already
let delay = ms => new Promise(res => setTimeout(res, ms))
for (i = 0; i < 10; i++) {                                                    
  if (doc.key) {
    break
  }                                                       
  await delay(1000)                                                               
  doc = await DbModel.findOne(pair)                                                                                                       
}

Is there a better way of achieving this using native es6 features (e.g. perhaps promisified versions of setTimeout and setInterval)?

标签: node.jsecmascript-6

解决方案


您可以尝试node-scheduer。与 cronjob 非常相似。但是应用程序必须保持运行。

它在给定的时间间隔内执行一个事件。确保每次在所需的时间间隔后执行作业,并将重复的功能放在那里。


推荐阅读