异常后的 ScheduledFuture 状态抑制了进一步执行

问题描述

scheduleAtFixedrate()scheduleWithFixedDelay()scheduledexecutorservice 的文档说:

如果任务的任何执行遇到异常,则禁止后续执行

也许是一个简单的问题,但我如何以编程方式检测到这种情况发生了(不调用 ScheduledFuture.get())? isCancelled() 返回 true 是否反映了这种情况?

解决方法

为了回答这个问题,我写了一个小单元测试:

{!hideCurrentLocation && (
  <>
    {[currentLocation?.city,currentLocation?.country_code2]
      .filter(Boolean)
      .join(",")}
  </>
)}

结论:

  • 发生异常后,import static org.assertj.core.api.BDDAssertions.then; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; class ScheduledExecutorServiceLT { @Test void test() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor(); final ScheduledFuture<?> scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(() -> { if (counter.incrementAndGet() == 3) { throw new RuntimeException(); } },0L,100L,TimeUnit.MILLISECONDS); then(scheduledFuture.isCancelled()).isFalse(); then(scheduledFuture.isDone()).isFalse(); Thread.sleep(500L); then(counter.get()).isEqualTo(3); then(scheduledFuture.isCancelled()).isFalse(); then(scheduledFuture.isDone()).isTrue(); } } 不会再次执行
  • 与我的预期相反,取消保持Runnable,但是
  • done 变为 false,如果引发异常