java - 当响应成功时取消调度程序执行器

标签 java scheduled-tasks

我有预定的执行人服务。它会每 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/

相关文章:

java - 在java中使用Scanner读取空格分隔的行

php - 如何在 WAMP/Windows 环境中每天自动运行 PHP 脚本?

Java 作业调度 : Is this possible with Quartz, 如果不是,我的替代方案是什么?

Java:以不同的时间间隔运行任务

c# - 支持回调或事件的商业 .net 任务调度程序组件

python - 找不到记录器 "apscheduler.executors.default"的处理程序?

java - Jython UnboundLocalError - 尝试了全局类型但仍然不起作用

maven-2 - 指定 JDK 供 Maven 使用

java - 使用 jsoup 提取 href

java - "? extends A"的目的是什么?