Flux / Mono中的动态间隔



如何设置动态间隔?例如,当我在间隔中放入一个原子值时它只对第一个值起作用即使当我更改一个更大的值时,它每5s起作用

我建议这样https://stackoverflow.com/a/47351359/8851815

public static void main(String[] args) throws InterruptedException {
final AtomicInteger time = new AtomicInteger(0);
System.out.println("START "+ LocalTime.now());
Flux.interval(Duration.of(5,ChronoUnit.SECONDS))
.startWith(0L)
.delayUntil(s -> Mono.just(s).delayElement(Duration.of(time.get(),ChronoUnit.SECONDS)))
.subscribe(s -> test(s,time));
Thread.sleep(70000);
}
public static void test(long s, AtomicInteger time){
try{
if(s <= 1) {
Thread.sleep(10000);
time.addAndGet(5);
} else {
time.set(0);
}
System.out.println("TIME " +  LocalTime.now());
} catch (Exception e){
System.out.println(e);
}
}
}

结果:

START 15:18:55.710771800
TIME 15:19:06.356155800 ->10s
TIME 15:19:21.376629100 ->15s
TIME 15:19:41.385095    ->20s
TIME 15:19:56.400575500 ->5s
TIME 15:19:56.401578800 ->5s
TIME 15:19:56.402576700 ->5s
TIME 15:19:56.402576700 ->5s
TIME 15:19:56.403571400 ->5s
TIME 15:19:56.403571400 ->5s
TIME 15:19:56.404569800 ->5s
TIME 15:19:56.404569800 ->5s
TIME 15:19:56.404569800 ->5s
TIME 15:19:56.404569800 ->5s [how to skip / drop those requests?]
TIME 15:20:01.371023600 ->5s
TIME 15:20:06.360791800 ->5s

你的代码很难理解,但基本上你想要实现的-是延迟你的Mono的动态间隔。当然,这是可能的。

我将用下面的例子来简化:

public static void main(String[] args) throws InterruptedException {
final AtomicInteger time = new AtomicInteger(0);
System.out.println("START "+ LocalTime.now());
Flux.interval(Duration.of(5,ChronoUnit.SECONDS))
.startWith(0L)
.delayUntil(s -> Mono.just(s).delayElement(randomDuration()))
.subscribe(s -> test(s,time));
Thread.sleep(70000);
}
// generate random Duration in millis between 3000 and 7000 ms
public static Duration randomDuration() {
long min = 3000;
long max = 7000;
long randomMillis = ThreadLocalRandom.current().nextLong(min, max + 1);
return Duration.ofMillis(randomMillis);
}

输出如下:

START 01:48:53.160028
TIME 01:48:59.786793
TIME 01:49:04.279440
TIME 01:49:07.771783
TIME 01:49:13.483046
TIME 01:49:17.003886
TIME 01:49:23.819252
TIME 01:49:29.021108
TIME 01:49:33.972711
TIME 01:49:40.832304
TIME 01:49:44.501199
TIME 01:49:51.029825
TIME 01:49:56.869309

你可以看到不同的间隔

最新更新