Enabling Task Scheduling
To utilize scheduled tasks in Spring Boot, enable scheduling support by adding the @EnableScheduling annotation to your main application class.
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Creating Scheduled Tasks
Scheduled tasks must be defined with in Spring-managed beans. Create a component class and anontate methods with @Scheduled to define execution patterns.
@Component
@Slf4j
public class TaskScheduler {
private final DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
@Scheduled(fixedRate = 3000)
public void executePeriodically() {
log.info("Fixed rate execution: {}", LocalDateTime.now().format(timeFormat));
}
@Scheduled(fixedDelay = 3000)
public void executeWithDelay() {
log.info("Fixed delay execution: {}", LocalDateTime.now().format(timeFormat));
}
@Scheduled(initialDelay = 2000, fixedRate = 3000)
public void delayedExecution() {
log.info("Delayed periodic execution: {}", LocalDateTime.now().format(timeFormat));
}
@Scheduled(cron = "*/3 * * * * ?")
public void cronBasedExecution() {
log.info("Cron-based execution: {}", LocalDateTime.now().format(timeFormat));
}
}
The @Scheduled annottaion supports multiple configuration options:
- fixedRate: Executes tasks at fixed time intervals
- fixedDelay: Waits for a specified delay after completion before next execution
- initialDelay: Sets the delay before the first execution
- cron: Defines complex schedules using cron expressions