Sub topic 8
What happens when a task throws
This chapter assumes you can already declare @Scheduled methods and know that the scheduler runs them on a thread pool. You should also be comfortable with SLF4J logging and Spring @Configuration classes.
The default behavior
An exception in a recurring task does not stop the schedule. Spring wraps each fixedRate, fixedDelay and cron task in an error handler that logs the exception at ERROR level and suppresses it. The scheduler thread survives, and the next run fires at its normal time.
@Component
public class FlakyJob {
private static final Logger log = LoggerFactory.getLogger(FlakyJob.class);
private int runs = 0;
@Scheduled(fixedDelay = 5000)
public void sync() {
runs++;
log.info("run {}", runs);
if (runs % 2 == 0) {
throw new IllegalStateException("remote API unavailable");
}
}
}Run 2 logs a stack trace, then run 3 starts five seconds later as usual. Nothing marks the task as failed, and no retry happens beyond the next scheduled run.
Common mistakes
- Relying on the default log alone. The stack trace appears in the log, but no metric, alert or health check changes. A job can fail every night and nobody notices until someone reads the logs.
- Assuming a failed run is retried. With
fixedDelay, the next run is simply the next scheduled one. A partially finished run is not resumed or rolled back unless your code does that. - Expecting exceptions to reach the caller. There is no caller. The scheduler invoked the method, so you cannot catch the exception anywhere outside the task.
- Losing errors with
@Async. If you combine@Scheduledwith@Async, the scheduler thread returns immediately. Avoidasync method sends its exception to theAsyncUncaughtExceptionHandler, not to the scheduler's error handler. By default that handler only logs the exception.
Handling errors inside the task
The most direct approach is to catch exceptions where you can act on them. Catch the failure, record it, and decide whether the rest of the work should continue.
@Scheduled(fixedDelay = 60000)
public void importOrders() {
for (String source : sources) {
try {
importFrom(source);
} catch (Exception e) {
log.error("Import from {} failed", source, e);
failureCounter.increment();
}
}
}One bad source no longer prevents the others from running. The counter, here a Micrometer Counter, gives you something to alert on.
A global error handler
To treat every scheduled failure the same way, set an error handler on the scheduler. Spring Boot applies any TaskSchedulerCustomizer bean to its auto-configured scheduler.
import org.springframework.boot.task.TaskSchedulerCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Configuration
public class SchedulingErrorConfig {
private static final Logger log = LoggerFactory.getLogger(SchedulingErrorConfig.class);
@Bean
TaskSchedulerCustomizer schedulerErrorHandler() {
return scheduler -> scheduler.setErrorHandler(
t -> log.error("Scheduled task failed: {}", t.getMessage(), t));
}
}The handler receives the Throwable after the task has failed. Use it to increment a metric or send a notification. It cannot tell you which job failed, apart from the stack trace, so add context in the job itself when you need it.
Retrying
Spring's scheduler does not retry. Your options are:
- Let the next scheduled run act as the retry. This works when the task is idempotent and a short delay is acceptable.
- Put a retry inside the method, for example with Spring Retry's
@Retryableon a service method that the job calls. - Use a second
@Scheduledmethod that reprocesses records marked as failed.
Exercise
A @Scheduled(fixedDelay = 10000) method throws a RuntimeException on its third run. What happens to the fourth run, and what is the most likely way a team would miss the failure?
Show answer
The fourth run still starts about 10 seconds after the third run ends, because the scheduler logs and suppresses the exception for recurring tasks. The team would likely miss it because the only trace is an ERROR log entry. Without a metric, alert or custom error handler, nothing else signals the failure.