首页 > 解决方案 > 当一个任务引发异常时,如何让 ScheduledExecutorService 继续执行其他后续任务

问题描述

我有一个执行器每 5 秒执行一次任务

public class ScheduledTaskExecutor {

  public int execute(){
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
    executor.scheduleAtFixedRate(new Task().run,3,5, TimeUnit.SECONDS);
    return -1;
  }

}

这是任务。我抛出一个IllegalArgumentException如果X == 4

public class Task {

    private static final Logger LOG = LoggerFactory.getLogger(DcEmailTask.class);
    private int x = 0;


    public Runnable run = () -> {
        String currentThread = Thread.currentThread().getName();
        x++;
        System.out.println("Thread [" + currentThread + "] is executing the task: " + x);
        if (x == 4) throw new IllegalArgumentException();
    };

}

程序停止执行并且不打印堆栈跟踪。

标签: javaconcurrencyexecutorservice

解决方案


  1. 实现 ScheduledExecutorService 接口 (SESWrrapper),该接口在其构造函数中接受另一个 ScheduledExecutorService。
  2. 实现 Runnable 接口 (SafeRunnableWrapper),该接口在其构造函数中接受另一个 Runnable,并在其 run() 方法中捕获异常。
  3. 如上所述实现 Callable 接口(SafeCallableWrapper)。
  4. 在 SESWrrapper.(Runnable, long, TimeUnit) 方法中,使用 SafeRunnableWrapper 包装 Runnable 并调用嵌套的 ScheduledExecutorService.schedule()。

推荐阅读