Sub topic 8
What happens when a task throws
This chapter assumes you can already declare @Scheduled methods, know the difference between fixed-rate, fixed-delay and cron triggers, and understand the scheduler thread pool from earlier chapters. Here you will see what the scheduler does when a task throws, how to make failures visible, and where the default behavior can hide problems.
The default: log and keep going
For recurring tasks (fixedRate, fixedDelay and cron), Spring wraps your method in a runnable that catches every Throwable. It passes the exception to an error handler. The handler Spring installs for repeating tasks logs the failure at ERROR level with the message "Unexpected error occurred in scheduled task" and then suppresses it.
Three consequences follow:
- The scheduler thread survives. The next run is still planned.
- Nothing outside the log learns about the failure. No caller exists, and the return value of a
@Scheduledmethod is ignored. - The application keeps reporting healthy, because from Spring's point of view nothing crashed.
@Component
public class FlakyJob {
private static final Logger log = LoggerFactory.getLogger(FlakyJob.class);
private final AtomicInteger runs = new AtomicInteger();
@Scheduled(fixedDelay = 3000)
public void run() {
int n = runs.incrementAndGet();
log.info("run {}", n);
if (n % 2 == 0) {
throw new IllegalStateException("simulated failure in run " + n);
}
}
}With this job you see a stack trace on every second run, and the job keeps running every three seconds after each end. A single failure never cancels a recurring schedule.
How each trigger reacts
The failure itself is handled the same way for all three triggers. The timing of the next run differs.
| Trigger | When the next run starts after a failure |
|---|---|
| `fixedRate` | At the next scheduled start time, measured from the previous start. A failing run that ended quickly changes nothing. |
| `fixedDelay` | After the configured delay, counted from the moment the failed run ended. |
| `cron` | At the next time the expression matches. |
This means a task that fails immediately and permanently, such as one that cannot reach its database, fails again at every interval. You get a steady stream of identical stack traces. Plan for that in your log volume and alerting.
One-shot tasks behave differently
The suppression rule applies to repeating tasks. A task scheduled once, for example through TaskScheduler.schedule(Runnable, Instant), gets a handler that logs the error and then propagates it. The exception ends up in the returned ScheduledFuture, and future.get() throws an ExecutionException. If nobody calls get(), you only have the log line. Do not assume the "keeps running" behavior carries over to code you write against the TaskScheduler API.
Checked exceptions
A @Scheduled method may declare throws Exception. Spring invokes the method by reflection and rethrows the underlying exception. A checked exception arrives at the error handler wrapped in UndeclaredThrowableException. The stack trace still shows the original as the cause, but code in a custom handler that checks t instanceof IOException will not match. Use getCause() when you need the original type.
Handle errors inside the task
The most reliable place to deal with failures is the task itself. The scheduler cannot know which part of your work is critical and which can be skipped. A common mistake is processing a batch in one loop and letting one bad item abort the rest.
@Component
public class InvoiceJob {
private static final Logger log = LoggerFactory.getLogger(InvoiceJob.class);
private final InvoiceService service;
public InvoiceJob(InvoiceService service) {
this.service = service;
}
@Scheduled(cron = "0 */10 * * * *")
public void sendPending() {
int failed = 0;
for (Invoice invoice : service.findPending()) {
try {
service.send(invoice);
} catch (RuntimeException e) {
failed++;
log.warn("Could not send invoice {}", invoice.id(), e);
}
}
if (failed > 0) {
log.error("{} invoices failed and will be retried in the next run", failed);
}
}
}Here InvoiceService and Invoice stand for your own types. Three points matter in this pattern:
- Each item has its own
try/catch, so one failure does not block the others. - Failed items stay in the "pending" state, so the next run retries them. The schedule itself acts as the retry mechanism.
- The summary line at
ERRORlevel is a single, searchable signal that a log-based alert can watch.
Catch the narrowest exception type that makes sense. Catching Exception or Throwable everywhere can hide programming errors such as a NullPointerException, which you want to see loudly.
For retries within a single run, with backoff and a maximum attempt count, use a retry library such as Spring Retry on the called service rather than writing a loop inside the scheduled method.
Replace the error handler
To centralize reporting, such as incrementing a metric or notifying a channel, give the scheduler your own ErrorHandler. Defining a ThreadPoolTaskScheduler bean makes Spring Boot's auto-configured scheduler back off, so set the pool properties you need on this bean directly. The spring.task.scheduling.* properties from the thread pool chapter no longer apply to it.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class SchedulerErrorConfig {
private static final Logger log = LoggerFactory.getLogger(SchedulerErrorConfig.class);
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(4);
scheduler.setThreadNamePrefix("sched-");
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.setAwaitTerminationSeconds(30);
scheduler.setErrorHandler(t -> {
Throwable cause = (t instanceof java.lang.reflect.UndeclaredThrowableException u
&& u.getCause() != null) ? u.getCause() : t;
log.error("Scheduled task failed: {}", cause.toString(), cause);
// increment a failure counter or send an alert here
});
return scheduler;
}
}The handler receives the failure of every recurring task that runs on this scheduler. The wrapper still suppresses the exception afterwards for repeating tasks, so your handler decides what gets recorded, not whether the schedule continues.
Exceptions with @Async
When a scheduled method is also @Async, the scheduler thread only submits the work and returns. Anything thrown later happens on the async executor, and the scheduler's error handler never sees it. For a void async method, Spring routes the exception to an AsyncUncaughtExceptionHandler. The default implementation logs it at ERROR level. Customize it by implementing AsyncConfigurer:
import java.lang.reflect.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class AsyncErrorConfig implements AsyncConfigurer {
private static final Logger log = LoggerFactory.getLogger(AsyncErrorConfig.class);
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return (Throwable ex, Method method, Object... params) ->
log.error("Async task {} failed", method.getName(), ex);
}
}If the async method returns a CompletableFuture, the exception is stored in the future instead and goes to the handler only if nobody consumes it. Nothing consumes a future returned to the scheduler, so a failure can vanish without a trace unless you attach exceptionally or whenComplete inside the method.
Failures that never throw
Not every failure is an exception. Watch for these cases:
- A task that hangs. A blocking call without a timeout never returns, so no exception reaches any handler. With a pool of one thread, every other scheduled task stops running. Always set timeouts on HTTP clients and database calls made from scheduled methods.
- A task that stalls under fixed rate. If a run takes longer than the interval, runs queue up and start late. They do not run in parallel on the same method.
- A transaction that rolls back. If the scheduled method calls a
@Transactionalservice, the rollback happens, then the exception reaches the error handler like any other. A caught exception inside a transactional method can leave you with a commit you did not expect.
Making failures visible
A reasonable baseline for production scheduled tasks:
- Log the start and end of each run with a duration, so a missing "finished" line is noticeable.
- Record a metric for successes and failures, and alert on repeated failures rather than on a single one.
- Record the time of the last successful run, and alert when it gets too old. This catches hangs and a disabled scheduler, which an error-based alert cannot.
- Keep the work idempotent, so that a retry in the next run is safe.
Exercise
A @Scheduled(fixedDelay = 10000) method throws a RuntimeException on its first run. What happens to the schedule, where can you see the failure, and why would a failure in the same method annotated with both @Scheduled and @Async not reach a custom scheduler ErrorHandler?
Show answer
The schedule continues. The recurring-task wrapper catches the exception, logs it at ERROR level, and suppresses it, so the next run starts 10 seconds after the failed run ended. You see the failure only in the log, unless you register your own handler. With @Async, the scheduler thread merely hands the work to the async executor and returns, so the exception happens on another thread. It is routed to the AsyncUncaughtExceptionHandler (default: log at ERROR), not to the scheduler's ErrorHandler.
Exercise
Why is a per-item try/catch inside a batch task usually better than letting the exception reach the scheduler's error handler?
Show answer
The scheduler only knows that the whole method failed. An exception thrown by item 3 stops the loop, so items 4 to 100 are not processed in that run. A per-item try/catch isolates each failure, lets the rest of the batch finish, and leaves the failed items in a state where the next run can retry them.