Sub topic 1
Turning on scheduling
Prerequisites
Assume you know basic Java, Spring beans, Spring Boot application structure, and application.yml or application.properties. You should also understand that a scheduled task runs on a background thread.
Turning on scheduling
Spring does not process @Scheduled annotations automatically. Add @EnableScheduling to a configuration class, usually the main application class. Spring then finds scheduled methods on beans and registers them with a scheduler.
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}Declaring tasks with `@Scheduled`
A scheduled method must belong to a Spring-managed bean, such as a class annotated with @Component. It normally has no parameters and returns void. The return value, if present, is ignored.
@Component
public class ReportJobs {
private static final Logger log =
LoggerFactory.getLogger(ReportJobs.class);
@Scheduled(fixedRate = 5000)
public void pollEveryFiveSeconds() {
log.info("Polling for new reports");
}
@Scheduled(fixedDelay = 5000, initialDelay = 10000)
public void refreshCache() {
log.info("Refreshing cache");
}
}The scheduler invokes these methods while the application is running. Calling a scheduled method directly from another object does not create a scheduled invocation.
Fixed rate, fixed delay and initial delay
The trigger determines when Spring starts each invocation.
| Trigger | Timing rule | Useful when |
|---|---|---|
| `fixedRate` | Measures from one start time to the next | Polling at regular intervals |
| `fixedDelay` | Waits after one invocation finishes | The next run depends on completion |
| `initialDelay` | Waits before the first invocation | Startup warm-up or delayed polling |
fixedRate = 5000 requests a five-second interval between start times. fixedDelay = 5000 waits five seconds after the method finishes. initialDelay can be combined with either trigger and affects only the first run.
Exercise
Which trigger should you choose when each run must finish before the next five-second wait begins?
Show answer
Choose fixedDelay = 5000. It starts the next run five seconds after the previous invocation finishes.