我正在使用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);
}
});
我想知道如何才能使超时必须在下一次队列检查之前完成。我可以使用去抖动,还是有更好的方法?
你可以使用
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();