2

以间隔进行重复(无限)异步作业的最优雅的方式是什么(在Calmm stack、Kefir、Karet Utils 等)?

我想要get一些 json 每个2000ms.

示例 1(2000 毫秒间隔):

  1. 获取 json(get需要 100 毫秒)
  2. 处理json
  3. 等待间隔剩余的时间,然后从步骤 1 重新开始

示例 2(2000ms 间隔)

  1. 获取 json(get需要 5000 毫秒)
  2. 处理json
  3. 等到第 1 步和第 2 步完成后再从第 1 步开始

所以简而言之,我想重复s (或任何异步工作)并在请求之间get等待最少的时间。2000ms

我不希望在前一个请求以某种方式完成(成功、失败、超时)之前触发下一个请求。

4

1 回答 1

1

This is how I would do that with Kefir without resorting to Kefir.stream. Note that job below would be the task you do at each tick. I stubbed a dummy task for the code to work.

let result = Kefir.repeat(() => {
    let job = Kefir.later(Math.random() * 5000);
    let wait = Kefir.later(2000).ignoreValues();
    return Kefir.merge([job, wait]);
});

Below is a visualization of the events using the style from the Kefir documentation:

spawned 1 - job:   ------1X
spawned 1 - wait:  -----------X
spawned 1 - merge: ------1----X
spawned 2 - job:               ------------------2X
spawned 2 - wait:              -----------X
spawned 2 - merge:             ------------------2X
spawned 3 - job:                                   ---3X
spawned 3 - wait:                                  -----------X
spawned 3 - merge:                                 ---3-------X
result:            ------1-----------------------2----3--------...
于 2017-08-04T18:04:20.900 回答