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 - Scheduling

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.

Setting up Spring Boot with Scheduling:

  • 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);
    }
}

Different ways to schedule tasks:

  • Fixed Rate: Executes at a fixed interval of time, regardless of the task duration.
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());
    }
}
  • Fixed Delay: Executes at a fixed delay after the completion of the last task.
@Scheduled(fixedDelay = 5000) // 5 seconds after the last task completion
public void reportCurrentTimeWithFixedDelay() {
    System.out.println("Fixed Delay Task: " + System.currentTimeMillis());
}
  • Initial Delay: You can also set an initial delay before the task starts running for the first time.
@Scheduled(fixedRate = 5000, initialDelay = 1000) // initial delay of 1 second
public void reportCurrentTimeWithInitialDelay() {
    System.out.println("Task with Initial Delay: " + System.currentTimeMillis());
}
  • Cron Expression: For more complex scheduling requirements, you can use Cron expressions.
@Scheduled(cron = "0 * * * * ?") // every minute
public void reportCurrentTimeWithCronExpression() {
    System.out.println("Cron Task: " + System.currentTimeMillis());
}

Points to Remember:

  • Make sure the methods being scheduled are void and do not take any arguments.
  • By default, the scheduled tasks run in a single thread. If you want tasks to run in parallel, you can customize the TaskScheduler bean.
  • The @Scheduled annotation should not be used on methods where execution time might exceed the scheduling interval, as this may lead to overlapping executions.

Conclusion:

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.

  1. Configuring scheduled tasks in Spring Boot:

    • Description: Spring Boot provides a straightforward way to configure and execute scheduled tasks. This is useful for automating recurring tasks in your application.
    • Code:
      // Example scheduling configuration in Spring Boot
      @SpringBootApplication
      @EnableScheduling
      public class MyApplication {
          public static void main(String[] args) {
              SpringApplication.run(MyApplication.class, args);
          }
      }
      
  2. Using @Scheduled annotation in Spring Boot:

    • Description: Spring's @Scheduled annotation is used to define a method as a scheduled task. It allows you to specify the fixed rate, delay, or cron expression.
    • Code:
      // Example using @Scheduled in Spring Boot
      @Service
      public class MyScheduledService {
          @Scheduled(fixedRate = 5000) // Run every 5 seconds
          public void myScheduledTask() {
              // Task logic
          }
      }
      
  3. Cron expressions for scheduling in Spring Boot:

    • Description: Cron expressions offer a powerful way to express recurring schedules. They allow you to define complex and flexible time-based schedules.
    • Code:
      // Example using cron expression in Spring Boot
      @Scheduled(cron = "0 0 0 * * MON-FRI") // Run every weekday at midnight
      public void myCronScheduledTask() {
          // Task logic
      }
      
  4. Fixed rate vs. fixed delay scheduling in Spring Boot:

    • Description: 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.
    • Code:
      // 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
      }
      
  5. Conditional scheduling with Spring Boot:

    • Description: Conditional scheduling allows you to control whether a scheduled task should run based on certain conditions.
    • Code:
      // Example conditional scheduling in Spring Boot
      @Scheduled(fixedRate = 5000)
      public void myConditionalTask() {
          if (shouldRunTask()) {
              // Task logic
          }
      }
      
      private boolean shouldRunTask() {
          // Your condition logic
          return true;
      }
      
  6. Scheduling asynchronous tasks in Spring Boot:

    • Description: Spring Boot supports asynchronous scheduling using the @Async annotation. This allows tasks to run concurrently.
    • Code:
      // Example scheduling asynchronous task in Spring Boot
      @Scheduled(fixedRate = 5000)
      @Async
      public CompletableFuture<Void> myAsyncTask() {
          // Asynchronous task logic
          return CompletableFuture.completedFuture(null);
      }
      
  7. Dynamic scheduling and runtime adjustments in Spring Boot:

    • Description: You can dynamically adjust scheduling parameters at runtime by modifying properties or using conditional logic.
    • Code:
      // Example dynamic scheduling in Spring Boot
      @Scheduled(fixedRateString = "${myapp.task.interval}")
      public void myDynamicTask() {
          // Task logic
      }
      
  8. Handling exceptions and errors in scheduled tasks with Spring Boot:

    • Description: Proper exception handling is essential for scheduled tasks. Spring Boot provides ways to handle exceptions and log errors.
    • Code:
      // 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());
          }
      }