In this tutorial
Hi there! Ore here from Kooredev with yet another hack to make your coding journey easier. Today I will be talking about a problem with Spring’s @Scheduled tasks that catches many teams out in production.
The problem
A microservice with scheduled tasks stopped processing in production. Six scheduled services were packaged in this microservice and deployed on an EC2 instance.
Sometimes, even after restarting the instance, the microservice still did not start processing again.
In the logs we could see the task running at the configured interval, and then it simply disappeared for good until we restarted the server once or a couple of times:
2023-06-11 17:24:57,031 [scheduling-1] INFO X.XXX.XXXX.StatusService - Task is running
2023-06-11 17:24:57,486 [scheduling-1] INFO X.XXX.XXXX.StatusService - Task is running
2023-06-11 17:24:57,955 [scheduling-1] INFO X.XXX.XXXX.StatusService - Task is running
2023-06-11 17:24:58,420 [scheduling-1] INFO X.XXX.XXXX.StatusService - Task is running
No exception, no error message, nothing. Just silence.
Troubleshooting
1. Check the thread pool size
By default, Spring runs all @Scheduled tasks on a thread pool of size 1. Remember there are six tasks in this microservice, so the pool needs to be bigger.
In the log, scheduling-1 is the default thread name, and this single thread is reused all the time. If any task runs too long (a slow database query, an HTTP call to a partner API with no timeout, a deadlock), it holds the only thread. Every other scheduled task waits behind it, and if the stuck task never finishes, all scheduled tasks stop.
That explains the symptoms: no error is thrown, because technically nothing failed. The scheduler is simply waiting.
2. Log the execution time of every @Scheduled method with AOP
To confirm which task was the culprit, we measured how long each one took. Add the AOP starter to the microservice (Spring Boot manages the version):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Then add an aspect that wraps every method annotated with @Scheduled and logs how long it took:
@Aspect
@Component
public class LoggingAspect {
private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);
@Around("@annotation(org.springframework.scheduling.annotation.Scheduled)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
return joinPoint.proceed();
} finally {
long took = System.currentTimeMillis() - start;
log.info("{} took {} ms", joinPoint.getSignature().toShortString(), took);
}
}
}
@annotation(org.springframework.scheduling.annotation.Scheduled) is the fully qualified name of the annotation the aspect matches, so every scheduled method in the application is measured without changing any of them.
A task that starts but never logs its “took … ms” line is a task that is stuck.
3. Find the long-running tasks
Watch your logs and find the tasks that take too long. A thread dump can also help: run jstack <pid> (or use your monitoring tool) and look at what the scheduling-1 thread is doing. The stack trace shows exactly which line it is stuck on. If you are not used to reading those, see how to read a Java stack trace.
The solution: increase the thread pool size
After troubleshooting, we knew which tasks took the most time and how many threads we needed. The fix is to increase the scheduler’s thread pool size. Add a config/ScheduledTaskConfig.java class to your microservice:
@Configuration
public class ScheduledTaskConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar registrar) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(6); // one thread per scheduled task
scheduler.setThreadNamePrefix("scheduled-task-");
scheduler.initialize();
registrar.setTaskScheduler(scheduler);
}
}
On Spring Boot you can get the same result without a config class by setting this property:
spring.task.scheduling.pool.size=6
Redeploy and keep an eye on the logs. Each task now runs on its own thread, so one slow task can no longer block the others. You will also see the thread names change from scheduling-1 to scheduled-task-1, scheduled-task-2 and so on.
Preventing it from happening again
A bigger pool stops one task from blocking the rest, but a task that hangs forever is still a bug. Some extra safeguards:
- Always set timeouts on external calls. HTTP clients, database queries and message brokers should all have connect and read timeouts. A call without a timeout can wait forever.
- Catch exceptions inside each task. An exception thrown from a
@Scheduledmethod is logged and the next run still happens, but catching and logging with context makes problems much easier to spot. - Use fixedDelay for jobs that must not overlap.
fixedRatestarts runs on a fixed clock;fixedDelaywaits for the previous run to finish before counting down to the next one. - Add monitoring and alerts. Record when each job last finished successfully, for example with Spring Boot Actuator and Micrometer metrics, and alert when it has not run for longer than expected.
- Consider ShedLock if you run several instances of the service. Without it, every instance runs every scheduled job, which can mean duplicate emails or payments.
- On Java 21+, consider virtual threads. Spring Boot 3.2+ can run scheduled tasks on virtual threads with
spring.threads.virtual.enabled=true, which makes blocking calls much cheaper.
Summary
- Spring’s default scheduler uses a single thread for all
@Scheduledtasks. - One slow or stuck task silently blocks all the others. There is no error message.
- Measure task durations with a simple AOP aspect, or take a thread dump, to find the culprit.
- Fix it by sizing the pool with a
SchedulingConfigurerorspring.task.scheduling.pool.size. - Prevent recurrences with timeouts, monitoring and, for multi-instance deployments, ShedLock.
Have you been bitten by this one? Tell us in the comments. And if you are just getting started with Spring Boot, try our first REST API tutorial.
