Sub topic 2
Declaring tasks with @Scheduled
The previous chapter turned scheduling on with @EnableScheduling. This chapter covers the annotation that declares a task: what it attaches to, which method shapes it accepts, and how Spring finds and registers it. I assume you know how Spring beans are created, how component scanning works, and how to read a stack trace from a failed application startup. The individual triggers (fixedRate, fixedDelay, cron) get their own chapters, so here they appear only as examples.
What @Scheduled does
@Scheduled marks a method on a Spring bean as a recurring task. You don't call the method yourself. After the application context starts, Spring registers the method with a scheduler, and the scheduler calls it repeatedly on one of its own threads.
The annotation does three jobs:
- It tells Spring which method to run.
- It tells Spring when to run it, through exactly one trigger attribute.
- It optionally adjusts details such as the time zone or a delay before the first run.
A first task
This is a complete task that logs a message every ten seconds.
package com.example.scheduling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class HeartbeatJob {
private static final Logger log = LoggerFactory.getLogger(HeartbeatJob.class);
@Scheduled(fixedRate = 10_000)
public void beat() {
log.info("heartbeat on thread {}", Thread.currentThread().getName());
}
}With @EnableScheduling on your application class, the log shows a line every ten seconds. With Spring Boot's defaults the thread name is scheduling-1. Boot creates a scheduler with a single thread, so every @Scheduled method in the application shares it. The [thread pool chapter](#) covers this in detail. For now, remember that a slow task can delay every other task.
Two properties of this example matter:
- The class is a Spring bean, because it carries
@Component. A plain object created withnewis never scanned. - The method has no parameters and returns nothing.
Method requirements
Spring checks each annotated method when it registers it. The rules are short.
| Requirement | Detail |
|---|---|
| Bean | The method must belong to a bean managed by the application context. |
| Parameters | None. Spring has nothing to pass in. |
| Return type | Use `void`. A returned value is ignored for ordinary methods. |
| Visibility | Public or package-private is safest. Non-public methods work on plain beans, but a private method cannot be called through a proxy. |
| Trigger | Exactly one of `cron`, `fixedDelay` or `fixedRate` (or their `String` variants). |
| Checked exceptions | The method may not declare a useful way to handle them. Catch or wrap them yourself. |
A void return type is a convention worth following. Returning a value suggests the caller will use it, and nobody does. Newer Spring versions give special treatment to reactive return types and Kotlin suspending functions, but ordinary Java services should stay with void.
What a violation looks like
Rule violations fail at startup, not at the first run. This method takes a parameter:
@Component
public class BrokenJob {
@Scheduled(fixedRate = 5000)
public void run(String name) {
// never reached
}
}The context fails to start with an IllegalStateException whose message includes Encountered invalid @Scheduled method 'run': Only no-arg methods may be annotated with @Scheduled. Failing early is useful, since a misdeclared task can't hide until production.
A missing trigger fails the same way, with a message saying that exactly one of the cron, fixedDelay(String) or fixedRate(String) attributes is required. Setting two triggers on one annotation fails too, because Spring cannot decide which one wins.
How registration works
Spring does not scan for @Scheduled itself. @EnableScheduling imports a bean post processor, ScheduledAnnotationBeanPostProcessor. A bean post processor sees every bean after it has been created, so the annotation is only found on beans that exist.
Tasks are not started the moment a bean is processed. The post processor collects them and starts them once the whole context has finished refreshing. This guarantees that your task never fires while the application is still wiring beans together.
Consequences worth knowing
- Lazy beans. A bean marked
@Lazyis created only on first use. If nothing ever uses it, its@Scheduledmethods are never registered. - Prototype beans. A prototype-scoped bean is created per injection, so schedules would be registered once per instance. Keep scheduled classes as singletons.
- Several contexts. If the same class is a bean in two application contexts, such as a parent and a child, the task is registered twice and runs twice.
- Proxies. Beans wrapped in AOP proxies (for example by
@Transactional) still schedule correctly. Spring resolves the method on the target class and invokes it through the proxy, so advice applies. This works only for methods the proxy can see, which is why private methods are risky.
One task never overlaps itself
A single registered task is never run concurrently with itself by the scheduler. If a run takes longer than the interval, the next run starts late. The scheduler does not start a second copy on another thread. The trigger chapters explain how fixedRate and fixedDelay differ when this happens.
Several schedules on one method
@Scheduled is a repeatable annotation. You can put it on one method more than once, and each occurrence becomes a separate task:
@Component
public class DigestJob {
@Scheduled(cron = "0 0 8 * * MON-FRI")
@Scheduled(cron = "0 0 10 * * SAT,SUN")
public void sendDigest() {
// weekday digest at 08:00, weekend digest at 10:00
}
}These are two registrations that happen to share a method. Each has its own timing, and they don't wait for each other. If the method is slow, the two could run at the same time on different scheduler threads when the pool is larger than one.
Choosing where a task lives
Because scheduling is attached to a method, you have a design choice. Two patterns are common.
- Schedule directly on the work. The annotated method contains the logic. This is fine for small jobs.
- Schedule a thin trigger. The annotated method only calls a service method. Tests can then call the service directly without involving a scheduler.
The second pattern also keeps timing concerns out of your business code:
@Component
public class ExpiryScheduler {
private final ExpiryService expiryService;
public ExpiryScheduler(ExpiryService expiryService) {
this.expiryService = expiryService;
}
@Scheduled(fixedDelay = 60_000)
public void run() {
expiryService.removeExpired();
}
}ExpiryService can now be unit tested, called from an admin endpoint, or reused by a different trigger, and none of that touches scheduling.
Common mistakes
- Forgetting
@EnableScheduling. Nothing fails and nothing runs. The annotation is simply ignored, so check this first when a task is silent. - Annotating a class that is not a bean. Missing
@Component, or a package outside component scanning, gives the same silence. - Expecting a parameter or a return value. Parameters fail at startup. Returned values are discarded.
- Doing slow work on the default single thread. One long task delays every other scheduled task in the application.
- Catching nothing. An unhandled exception ends that one run and is logged. The next run still happens. A later chapter covers this behavior and how to log failures usefully.
Exercise
Your application has a bean with a correct @Scheduled(fixedRate = 5000) method, but the log never shows it running and startup is clean. Name two likely causes.
Show answer
Either @EnableScheduling is missing from the configuration, so the annotation is never processed, or the class is not a Spring bean, for example because @Component is missing or it sits outside the scanned packages. A @Lazy bean that nothing injects is a third possibility. A bad method signature is not a cause here, because that would stop startup with an IllegalStateException.
Exercise
Why does this method prevent the application from starting, and how would you fix it? @Scheduled(fixedRate = 1000, cron = "0 *") public void tick() { }
Show answer
Spring requires exactly one trigger attribute per @Scheduled annotation, and this one sets two. Remove one of them. If you really need both schedules, split them into two annotations on the same method, each with a single trigger, since @Scheduled is repeatable.