NodeJS排队异步函数

时间:2016-01-10 00:30:19

标签: node.js asynchronous queue

我正在开发一个NodeJS函数,它具有一系列需要运行的异步任务。

我读了一个从数据库中提取的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秒runFrequency只是一个目标,它不需要恰好是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,但我不确定这是不是我想要的。

谢谢,

1 个答案:

答案 0 :(得分:0)

如果您有一组预定的预定任务,则可以迭代它们并设置间隔。

'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);
}