从在 ScheduledExecutorService 中运行的任务本身中停止周期性任务 [英] Stop a periodic task from within the task itself running in a ScheduledExecutorService

查看:23
本文介绍了从在 ScheduledExecutorService 中运行的任务本身中停止周期性任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 ScheduledExecutorService 中运行时,是否有一种很好的方法可以阻止任务本身的重复任务?

Is there a nice way to stop the repetition of task from within the task itself when running in a ScheduledExecutorService?

比方说,我有以下任务:

Lets say, I have the following task:

Future<?> f = scheduledExecutor.scheduleAtFixedRate(new Runnable() {
    int count = 0;
    public void run() {
       System.out.println(count++);
       if (count == 10) {
           // ??? cancel self
       }
    }
}, 1, 1, TimeUnit.SECONDS);

在外面,通过f.cancel()很容易取消,但是如何在指定的地方停止重复呢?(通过 AtomicReference 传递 Future 是不安全的,因为当 scheduleAtFixedRate 返回 f 延迟并且变量设置也延迟时有一个潜在的窗口,并且任务本身可能已经运行,在引用中看到空值.)

From outside, it is easy to cancel via f.cancel(), but how can I stop the repetition at the specified place? (Passing the Future through an AtomicReference is not safe, because there is a potential window when the scheduleAtFixedRate returns f late and the variable is set late too, and the task itself might already run, seeing a null in the reference.)

推荐答案

当一个重复的任务抛出异常或错误时,它被放置在 Future 中并且该任务不再重复.您可以抛出您选择的 RuntimeException 或 Error.

When a repeating task throws an Exception or Error, it is placed in the Future and the task is not repeated again. You can throw a RuntimeException or Error of your choice.

这篇关于从在 ScheduledExecutorService 中运行的任务本身中停止周期性任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆