java/spring scheduler 异常捕获处理

来源:互联网 发布:闪电网络 时间 编辑:程序博客网 时间:2024/06/05 19:39

由于java的异常会导致线程被打断,因此任务的异常是被任务工作线程捕获的。

若需要对任务运行情异常捕获可以这样操作:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();ScheduledFuture<?> handle =        scheduler.scheduleWithFixedDelay(new Runnable() {             public void run() {                  throw new RuntimeException("foo");             }        }, 1, 10, TimeUnit.SECONDS);// Create and Start an exception handler thread// pass the "handle" object to the thread// Inside the handler thread do :....try {  handle.get();} catch (ExecutionException e) {  Exception rootException = e.getCause();}

或者直接在任务中捕获处理:

final Runnable someChoreRunnable = () -> {    try {        doChore();    } catch ( Throwable t ) {  // Catch Throwable rather than Exception (a subclass).        logger.error( "Caught exception in ScheduledExecutorService. StackTrace:\n" + t.getStackTrace() );    }};

spring通过注解的方式可以通过scheduler的setErrorHandler处理:

@EnableScheduling@Configurationclass SchedulingConfiguration implements SchedulingConfigurer {    private final Logger logger = LoggerFactory.getLogger(getClass());    private final ThreadPoolTaskScheduler taskScheduler;    SchedulingConfiguration() {        taskScheduler = new ThreadPoolTaskScheduler();        taskScheduler.setErrorHandler(t -> logger.error("Exception in @Scheduled task. ", t));        taskScheduler.setThreadNamePrefix("@scheduled-");        taskScheduler.initialize();    }    @Override    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {        taskRegistrar.setScheduler(taskScheduler);    }}

亦是在代码中直接try-catch:

@Scheduled(cron = "${schedulerRate}")public void scheduledJob() {    try {        businessLogicService.doBusinessLogic();    } catch (Exception e) {        log.error(e);    }}