Exception handling for Spring 3.2 "@Scheduled" annotation

user3515080 picture user3515080 · Jun 4, 2014 · Viewed 12.5k times · Source

How to customize the exception handling for @Scheduled annotation from spring ?

I have Cron jobs which will be triggered in the server (Tomcat 6) and when any exceptions occur I need to do some handling.

  • Spring version 3.2
  • Tomcat Server 6

Answer

Mariusz.v7 picture Mariusz.v7 · Aug 13, 2017

If you want to use Java Config you will need to create configuration implementing SchedulingConfigurer

@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);
    }
}

You can modify error handler for your needs. Here I only log a message.

Don't forget to call taskScheduler.initialize();. Without it you'll get:

java.lang.IllegalStateException: ThreadPoolTaskScheduler not initialized