如何每秒安排一个任务,但在继续下一个任务之前等待 setTimeout() ?

问题描述 投票:0回答:1

我正在使用node.js,我有一个每秒运行的任务,如下所示:

let queue = ["Sample Data 1", "Sample Data 2"]
const job = schedule.scheduleJob('*/1 * * * * *', function () {
    console.log("Checking the queue...")
    if (queue.length > 0) {
        wss.broadcast(JSON.stringify({
            data: queue[0]
        }));
        setTimeout(() => {
            queue.shift();
        }, queue[0].duration);
    }
});

我想知道如何才能使超时必须在下一次队列检查之前完成。我可以使用去抖动,还是有更好的方法?

javascript node.js schedule
1个回答
0
投票

你可以使用

Math.max(queue[0].duration, 1000 - (performance.now() - start))

使作业之间的间隔至少为 1 秒并递归调用调度:


    let queue = ["Sample Data 1", "Sample Data 2"];

    const shiftQueue = () => {
        const start = performance.now();
        return schedule.scheduleJob('*/1 * * * * *', function () {
          console.log("Checking the queue...")
          if (queue.length > 0) {
              wss.broadcast(JSON.stringify({
                  data: queue[0]
              }));
              setTimeout(() => {
                  queue.shift();
                  shiftQueue();
              }, Math.max(queue[0].duration, 1000 - (performance.now() - start)));
          }
      });
    }

    shiftQueue();

© www.soinside.com 2019 - 2024. All rights reserved.