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.
The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.
We can turn any method in a Spring bean for scheduling by adding the @Scheduled annotation to it. The @Scheduled is a method-level annotation applied at runtime to mark the method to be scheduled. It takes one attribute from cron , fixedDelay , or fixedRate for specifying the schedule of execution in different formats.
The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown.
There is no need to use @Async. Just use fixedRate attribute of @Scheduled instead of fixedDelay. Spring will make another invocation on the method after the given time regardless of any call is already being processed.
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
You could implement and register an ErrorHandler
for the ThreadPoolTaskScheduler
that is used for your scheduling annotations.
<task:annotation-driven scheduler="yourThreadPoolTaskScheduler" />
<bean id="yourThreadPoolTaskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="5" />
<property name="errorHandler" ref="yourScheduledTaskErrorHandler" />
</bean>
<bean id="yourScheduledTaskErrorHandler"
class="com.example.YourScheduledTaskErrorHandler"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With