node.js - 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-scheduer。与 cronjob 非常相似。但是应用程序必须保持运行。
它在给定的时间间隔内执行一个事件。确保每次在所需的时间间隔后执行作业,并将重复的功能放在那里。
推荐阅读
- css - 无论使用css的屏幕大小如何,如何将图标放在同一个位置?
- angular - 如何使用keycloak在角度4中的每个路由级别进行身份验证和授权
- node.js - Stop-Process 不停止进程
- mongodb - MongoDB“Starting new replica set monitor for”消息含义
- angular - 在 Angular 应用程序中从 TXT 文件中读取 UTF-8 字符的问题
- java - WildFly中servlet过滤器处理HTML和JSP的区别
- parse-platform - 如何根据 POST 请求将当前用户传递给服务器?
- javascript - 如何在每次循环迭代中删除数组的前三个索引 - JS
- solace - Solace - 当我收到“发送消息时出错 - 已关闭”时如何自动重新连接
- service - 在 systemd 服务文件中使用之前/之后是否有任何先决条件?