我有预定的执行人服务。它会每 30 秒调用一次 Rest api。响应要么是等待,要么是成功。一旦响应成功,我需要取消执行器。
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(
() -> //Calling a RestApi returing a response of SUCCESS or WAITING
, 0, 30, TimeUnit.SECONDS);
最佳答案
您的问题的一般答案可以在 How to remove a task from ScheduledExecutorService? 上找到
但是要回答您的具体问题,“我如何在任务中完成它?” - 这有点棘手。您希望避免出现任务在 scheduleAtFixedRate
之前完成的(不太可能的)竞争情况。方法完成并引用 ScheduledFuture
可存储在字段中。
下面的代码通过使用 CompletableFuture
解决了这个问题存储对 ScheduledFuture
的引用代表任务。
public class CancelScheduled {
private ScheduledExecutorService scheduledExecutorService;
private CompletableFuture<ScheduledFuture<?>> taskFuture;
public CancelScheduled() {
scheduledExecutorService = Executors.newScheduledThreadPool(2);
((ScheduledThreadPoolExecutor) scheduledExecutorService).setRemoveOnCancelPolicy(true);
}
public void run() {
taskFuture = new CompletableFuture<>();
ScheduledFuture<?> task = scheduledExecutorService.scheduleAtFixedRate(
() -> {
// Get the result of the REST call (stubbed with "SUCCESS" below)
String result = "SUCCESS";
if (result.equals("SUCCESS")) {
// Get the reference to my own `ScheduledFuture` in a race-condition free way
ScheduledFuture<?> me;
try {
me = taskFuture.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
me.cancel(false);
}
}, 0, 30, TimeUnit.SECONDS);
// Supply the reference to the `ScheduledFuture` object to the task itself in a race-condition free way
taskFuture.complete(task);
}
关于java - 当响应成功时取消调度程序执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015684/