NodeJS队列asynchronous函数
我正在研究一个NodeJS函数,它有一系列需要运行的asynchronous任务。
我从数据库中读取了一系列tasks
,每个task
都有一个“runFrequency”属性。
例如 :
var tasks: [ task1: { type: doSomething, ..., runFrequency: 10 // Needs to run every 10 seconds. }, task2: { type: doSomethingElse, ..., runFrequency: 30 // Needs to run every 30 seconds. }, task3: { type: doSomething, ..., runFrequency: 10 } ];
我需要调用一个processTask()
函数在每个runFrequency
设置中运行每个任务,但一次只能运行一个任务。 (10秒的运行频率只是一个目标,不需要精确到10秒)。
例
12:00:00: processTask(task1); 12:00:02: task1 completes, task1 scheduled to run again at 12:00:12, 12:00:02: processTask(task2); 12:00:05: task2 completes, task2 scheduled to run again at 12:00:35, 12:00:05: processTask(task3); 12:00:10: task3 completes, task3 scheduled to run again at 12:00:20, // all tasks finished, next task isn't scheduled to start until 12:00:12, 12:00:12: processTask(task1); 12:00:25: task1 completes, task1 scheduled to run again at 12:00:35, 12:00:25: task2 was scheduled to start at 12:00:20, it's the next task in the queue so it needs to be run now.
在NodeJS中设置这种“任务队列”的最好方法是什么?
我已经看过Kue和Redis,但我不确定这是否正是我想要的。
谢谢,
如果你有一组预定的任务,你可以迭代它们并设置时间间隔。
'use strict'; let tasks = [ { name: 'Check StackOverflow', frequency: 1, taskFn: () => console.log('Checking StackOverflow...') }, { name: 'Check Email', frequency: 3, taskFn: () => console.log('Checking email...') }, { name: 'Download the Internet!', frequency: 5, taskFn: () => console.log('Downloading the internet') } ]; for (let task of tasks) { console.log(`Scheduling ${task.name}`); setInterval(task.taskFn, task.frequency * 1000); }