java Flux / Mono中的动态间隔

j0pj023g  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(149)

如何创建一个动态间隔?例如,当我在间隔中放入一个原子值时,它只对第一个值起作用,即使当我更改为一个更大的值时,它每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
biswetbf

biswetbf1#

你的代码很难理解,但基本上你想要实现的是动态间隔来延迟你的单声道。当然,这是可能的。
我将用下面的例子来简化这个过程:

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

您可以在此处看到不同的间隔

相关问题