← 中文资源

简体中文版本

调度任务异常会终止后续执行

周期任务抛出未捕获异常会被静默取消:裸任务只执行一次就停,包上 try/catch 把异常消化掉才能按节奏继续;两个运行计数并排打印,对比一目了然。

阅读英文原文

实现说明

真正干活的是类 SchedulerExceptionSuppressor,其余都是接线。 守卫条件成立时抛出 IllegalStateException,而不是返回一个假值。

使用要点

  • 每一步打印都带着自己的标签:caught:、bare task stopped at:、guarded task kept going:。

常见问题

坏输入有失败路径吗?

校验先行——IllegalStateException 标记失败,不会先做一半再失败。

运行「调度任务异常会终止后续执行」会打印什么?

运行文件本身,caught:、bare task stopped at:、guarded task kept going: 这些前缀各对应一段演示逻辑。

核心语句

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
throw new IllegalStateException("boom on run " + bareRuns.get());
throw new IllegalStateException("still failing");

代码示例

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SchedulerExceptionSuppressor {

    public static void main(String[] args) throws Exception {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        AtomicInteger bareRuns = new AtomicInteger();
        AtomicInteger guardedRuns = new AtomicInteger();

        // an uncaught exception suppresses later runs: the task is cancelled silently
        scheduler.scheduleAtFixedRate(() -> {
            bareRuns.incrementAndGet();
            throw new IllegalStateException("boom on run " + bareRuns.get());
        }, 0, 50, TimeUnit.MILLISECONDS);

        // catching inside the task keeps the schedule alive after individual failures
        scheduler.scheduleAtFixedRate(() -> {
            try {
                if (guardedRuns.incrementAndGet() <= 2) {
                    throw new IllegalStateException("still failing");
                }
            } catch (RuntimeException e) {
                System.out.println("caught: " + e.getMessage());
            }
        }, 0, 50, TimeUnit.MILLISECONDS);

        Thread.sleep(400);
        scheduler.shutdownNow();

        // bare stays stuck at 1; guarded climbs close to the scheduled period count
        System.out.println("bare task stopped at:    " + bareRuns.get() + " run(s)");
        System.out.println("guarded task kept going: " + guardedRuns.get() + " runs");
    }
}