场景:我调用2个API之间需要等待10秒。因为 BE 需要时间来更新,如果我们立即调用第二个 API,它不会给出预期的输出。
我使用“Thread.sleep”进行等待,它工作正常。但想检查是否有其他方法可以实现它。
Awaitility lib 就是你想要的,它根据条件等待(类似于 selenium 中的显式等待)。
您可以使用ScheduledExecutorService类:
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(Classname::someTask, delayInSeconds, TimeUnit.SECONDS);
或者 TimeUnit.sleep() 与您已经使用的 Thread.sleep() 非常相似:
try {
TimeUnit.SECONDS.sleep(secondsToSleep);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
用途:
Awaitility.await().pollDelay(Duration.ofMillis(retryIntervalMillis)).until(() -> true);
或
Guava(注意可能的 SonarQube 问题):https://guava.dev/releases/19.0/api/docs/com/google/common/util/concurrent/Uninterruptibles.html