如何创建一个动态间隔?例如,当我在间隔中放入一个原子值时,它只对第一个值起作用,即使当我更改为一个更大的值时,它每5秒起作用
我建议这个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
1条答案
按热度按时间biswetbf1#
你的代码很难理解,但基本上你想要实现的是动态间隔来延迟你的单声道。当然,这是可能的。
我将用下面的例子来简化这个过程:
它将给予如下输出:
您可以在此处看到不同的间隔