Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
Spring Boot simplifies the task of scheduling in Java applications by leveraging the Spring Framework's powerful scheduling capabilities. Scheduling tasks to run at fixed times or intervals is straightforward using Spring's @Scheduled
annotation.
Add Dependency: No additional dependencies are required as the core scheduling capability comes with spring-boot-starter
.
Enable Scheduling: To enable the scheduling, add @EnableScheduling
to your main application class or a configuration class.
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class SchedulingApplication { public static void main(String[] args) { SpringApplication.run(SchedulingApplication.class, args); } }
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class ScheduledTasks { @Scheduled(fixedRate = 5000) // 5 seconds public void reportCurrentTimeWithFixedRate() { System.out.println("Fixed Rate Task: " + System.currentTimeMillis()); } }
@Scheduled(fixedDelay = 5000) // 5 seconds after the last task completion public void reportCurrentTimeWithFixedDelay() { System.out.println("Fixed Delay Task: " + System.currentTimeMillis()); }
@Scheduled(fixedRate = 5000, initialDelay = 1000) // initial delay of 1 second public void reportCurrentTimeWithInitialDelay() { System.out.println("Task with Initial Delay: " + System.currentTimeMillis()); }
@Scheduled(cron = "0 * * * * ?") // every minute public void reportCurrentTimeWithCronExpression() { System.out.println("Cron Task: " + System.currentTimeMillis()); }
TaskScheduler
bean.@Scheduled
annotation should not be used on methods where execution time might exceed the scheduling interval, as this may lead to overlapping executions.Scheduling in Spring Boot is made straightforward with the @Scheduled
annotation. By using this along with the @EnableScheduling
annotation, you can create periodic tasks effortlessly. However, for more complex scheduling needs or distributed tasks, you might consider more robust solutions like Quartz or Spring Batch.
Configuring scheduled tasks in Spring Boot:
// Example scheduling configuration in Spring Boot @SpringBootApplication @EnableScheduling public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Using @Scheduled annotation in Spring Boot:
@Scheduled
annotation is used to define a method as a scheduled task. It allows you to specify the fixed rate, delay, or cron expression.// Example using @Scheduled in Spring Boot @Service public class MyScheduledService { @Scheduled(fixedRate = 5000) // Run every 5 seconds public void myScheduledTask() { // Task logic } }
Cron expressions for scheduling in Spring Boot:
// Example using cron expression in Spring Boot @Scheduled(cron = "0 0 0 * * MON-FRI") // Run every weekday at midnight public void myCronScheduledTask() { // Task logic }
Fixed rate vs. fixed delay scheduling in Spring Boot:
fixedRate
schedules a task with a fixed period between invocations, while fixedDelay
schedules a task with a fixed delay between the end of the last execution and the start of the next.// Example using fixedRate and fixedDelay in Spring Boot @Scheduled(fixedRate = 5000) // Run every 5 seconds public void myFixedRateTask() { // Task logic } @Scheduled(fixedDelay = 10000) // Run every 10 seconds after the completion of the previous execution public void myFixedDelayTask() { // Task logic }
Conditional scheduling with Spring Boot:
// Example conditional scheduling in Spring Boot @Scheduled(fixedRate = 5000) public void myConditionalTask() { if (shouldRunTask()) { // Task logic } } private boolean shouldRunTask() { // Your condition logic return true; }
Scheduling asynchronous tasks in Spring Boot:
@Async
annotation. This allows tasks to run concurrently.// Example scheduling asynchronous task in Spring Boot @Scheduled(fixedRate = 5000) @Async public CompletableFuture<Void> myAsyncTask() { // Asynchronous task logic return CompletableFuture.completedFuture(null); }
Dynamic scheduling and runtime adjustments in Spring Boot:
// Example dynamic scheduling in Spring Boot @Scheduled(fixedRateString = "${myapp.task.interval}") public void myDynamicTask() { // Task logic }
Handling exceptions and errors in scheduled tasks with Spring Boot:
// Example exception handling in scheduled task @Scheduled(fixedRate = 5000) public void myTaskWithExceptionHandling() { try { // Task logic } catch (Exception e) { // Handle exception log.error("Error in scheduled task: {}", e.getMessage()); } }