Master Spring Boot 3.x Scheduled Tasks: From Basics to Advanced Configurations
This guide walks through enabling Spring Boot 3.x scheduling, creating simple and complex @Scheduled jobs, configuring thread pools, externalizing cron expressions, conditional execution, exception handling, and provides a complete runnable example with best‑practice tips.
Basic Configuration
To activate scheduling, add @EnableScheduling to the main application class and include the necessary imports.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}Define a component with methods annotated by @Scheduled to declare tasks.
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
// Execute every 5 seconds
@Scheduled(fixedRate = 5000)
public void taskWithFixedRate() {
System.out.println("Fixed‑rate task executed: " + new java.util.Date());
}
// Execute 2 seconds after the previous run finishes
@Scheduled(fixedDelay = 2000)
public void taskWithFixedDelay() {
try {
Thread.sleep(1000); // simulate work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Fixed‑delay task executed: " + new java.util.Date());
}
// Cron expression: run at the 30th second of every minute
@Scheduled(cron = "30 * * * * ?")
public void taskWithCronExpression() {
System.out.println("Cron task executed: " + new java.util.Date());
}
// Initial delay of 3 s, then every 10 s
@Scheduled(initialDelay = 3000, fixedRate = 10000)
public void taskWithInitialDelay() {
System.out.println("Task with initial delay executed: " + new java.util.Date());
}
}Advanced Configuration
1. Custom Task Thread Pool
Spring Boot’s default scheduler uses a single thread, which can cause blocking. Define a ThreadPoolTaskScheduler and register it via SchedulingConfigurer:
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
private final int POOL_SIZE = 10;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(POOL_SIZE);
scheduler.setThreadNamePrefix("my-scheduled-task-pool-");
scheduler.initialize();
taskRegistrar.setTaskScheduler(scheduler);
}
}2. Externalizing Cron or Interval Settings
Place cron expressions or intervals in application.properties or application.yml to adjust them without recompiling.
@Component
public class ConfigurableScheduledTask {
@Scheduled(cron = "${scheduler.cron.expression:0 * * * * ?}")
public void configurableTask() {
System.out.println("Configurable task executed: " + new java.util.Date());
}
}
# application.properties example
scheduler.cron.expression=0 */5 * * * ?3. Conditional Scheduling
Use @ConditionalOnProperty to enable or disable a task based on a configuration flag.
@Component
@ConditionalOnProperty(value = "scheduler.task.enabled", havingValue = "true", matchIfMissing = true)
public class ConditionalScheduledTask {
@Scheduled(fixedRate = 5000)
public void conditionalTask() {
System.out.println("Conditional task executed: " + new java.util.Date());
}
}Exception Handling
Uncaught exceptions stop a scheduled task. Wrap the logic in a try‑catch block and log failures.
@Component
public class ExceptionHandlingScheduledTask {
@Scheduled(fixedRate = 5000)
public void taskWithExceptionHandling() {
try {
System.out.println("Potentially failing task: " + new java.util.Date());
int result = 1 / 0; // simulated exception
} catch (Exception e) {
System.err.println("Task failed: " + e.getMessage());
}
}
}Complete Example
Main Application
@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
public static void main(String[] args) {
SpringApplication.run(SchedulingApplication.class, args);
}
}Configuration File (application.yml)
scheduler:
demo:
cron: "0 */1 * * * ?"
fixed-rate: 5000Important Considerations
Single‑Instance Issue – In a clustered deployment each instance runs the same jobs. Use a distributed lock (e.g., Redis or Zookeeper) to prevent duplicate execution.
Task Execution Time – If a job runs longer than its interval, tasks may pile up or run concurrently; choose fixedDelay or add locking as needed.
Application Shutdown – By default Spring Boot interrupts running tasks on shutdown. Configure ThreadPoolTaskScheduler.setAwaitTerminationSeconds() for graceful termination.
Following these steps, you can reliably schedule and manage background jobs in Spring Boot 3.x , tailoring the configuration to suit various business scenarios.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ray's Galactic Tech
Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
