Sub topic 2
Declaring tasks with @Scheduled
This chapter assumes you can write a Spring Boot application with @Component beans and that @EnableScheduling is already on your application class, as in the previous chapter. Here you will mark methods as scheduled tasks and learn which methods Spring accepts.
What @Scheduled does
@Scheduled is a method annotation. At startup, Spring scans every bean in the application context for methods that carry it. For each one, Spring registers a task with the scheduler. The scheduler then calls that method on the bean at the times the annotation describes.
Spring does not create the bean for you. The annotated method must live on a bean that Spring manages, such as a @Component, @Service, or a bean returned from a @Bean method.
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 = 10000)
public void heartbeat() {
log.info("still alive");
}
}With scheduling enabled, this logs a line about every ten seconds. The attribute fixedRate is one of three trigger styles. The next two chapters cover how they differ.
Method requirements
Spring checks each annotated method when the bean is processed. A method must meet these rules:
- It takes no parameters. The scheduler has nothing to pass in.
- It normally returns
void. A returned value is ignored, so there is no point returning one. - It is not private. Use a public or package-private method. Spring may wrap the bean in a proxy, and a private method cannot be called reliably through one.
- It belongs to a Spring-managed bean.
Each annotation must also name exactly one trigger: cron, fixedRate, or fixedDelay (or their String variants). If you give none, or more than one, startup fails with an IllegalStateException.
Common errors
| Symptom | Likely cause |
|---|---|
| Nothing ever runs and there is no error | `@EnableScheduling` is missing, or the class is not a bean (no `@Component`, or it is outside the component scan) |
| Startup fails with "Only no-arg methods may be annotated with @Scheduled" | The method has a parameter |
| Startup fails with "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required" | The annotation has no trigger, or has two |
| Tasks run late or one at a time | The default scheduler has a single thread, covered in a later chapter |
The first row is the hardest to spot because Spring stays silent. If a task does not run, check these two things first.
Several tasks and several triggers
One class can hold many scheduled methods. Each is registered as its own task.
@Component
public class HousekeepingJobs {
private static final Logger log = LoggerFactory.getLogger(HousekeepingJobs.class);
@Scheduled(fixedRate = 60000)
public void refreshCache() {
log.info("cache refreshed");
}
@Scheduled(fixedRate = 30000)
@Scheduled(cron = "0 0 * * * *")
public void flushMetrics() {
log.info("metrics flushed");
}
}@Scheduled is a repeatable annotation, so you can stack it on one method as flushMetrics does. That method runs on both schedules.
Where the call happens
Spring registers the task once, at startup. The scheduler then keeps calling the method on a scheduler thread. The method does not run on the thread that started the application.
Exercise
A teammate adds @Scheduled(fixedRate = 5000) to public void sync(String region) in a @Component. What happens at startup, and how do you fix it?
Show answer
Startup fails with an IllegalStateException because scheduled methods may not take parameters. Remove the parameter. Read the value from a field or from configuration inside the method, or call a separate method that takes the region and have the scheduled method call it.