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

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

问题描述

在ScheduledExecutorService中运行时,有没有很好的方法来阻止任务从任务本身重复?

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

我有以下任务: / p>

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传递未来是不安全的,因为当scheduleAtFixedRate返回f late并且变量被设置为late时,有一个潜在的窗口,并且任务本身可能已经运行,在引用中看到一个null。)

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.)

推荐答案

当重复任务抛出异常或错误时,它被放置在未来,任务不会再次重复。您可以抛出一个您选择的RuntimeException或错误。

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天全站免登陆