没有Thread.sleep()如何等待一段时间



我已经使用GCP java SDK作为启动/停止实例。我目前的问题是,我想在启动或停止后等待一段时间,直到将实例状态更改为RUNNINGSTOPPED。我想在不使用Thread.sleep()的情况下完成此操作。

这是我当前的代码:-

private void waitDone(Operation operation) throws IOException, 
InterruptedException {
String status = operation.getStatus();
while (!status.equals("DONE")) {
Thread.sleep(5 * 1000);
Compute.ZoneOperations.Get get = 
getCompute().zoneOperations().get(projectId, zone,
operation.getName());
operation = get.execute();
if (operation != null) {
status = operation.getStatus();
}
}
}

您可以使用ScheduledExecutiorService#scheduleWithFixedDelay。像这样的

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(() -> {
Compute.ZoneOperations.Get get = 
getCompute().zoneOperations().get(projectId, zone, operation.getName());
operation = get.execute();
if (operation != null && operation.getStatus().equals("DONE")) {
executor.shutdown();
}
}, 0, 5, TimeUnit.SECONDS);
//if you need to block current thread
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);

如果您不想在等待状态更改时阻止程序(这是有意义的(,请将等待放在一个单独的线程中。

如何创建线程并启动它在很多地方都有解释,所以我认为在这里重复代码没有任何意义。只要搜索一下。

正如Manish在评论中所说,为了解决无限期等待问题,如果状态更改为done或达到最大重试计数,则可以使用重试计数器并退出循环。

顺便说一句,我认为这个版本的等待稍微容易阅读:

TimeUnit.SECONDS.sleep(5);

它的工作原理与Thread.sleep(5 * 1000);相同。

最新更新