1. 程式人生 > >java/spring scheduler 異常捕獲處理

java/spring scheduler 異常捕獲處理

由於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
@Configuration
class 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);
    }
}