Spring Boot Scheduled Tasks are essential for automating repetitive jobs like database cleanup, report generation, or API polling. In this hands-on tutorial on Spring Boot Scheduled Tasks, you’ll learn to configure and optimize scheduled tasks using Spring Boot’s @Scheduled
annotation, cron expressions, and best practices for production-ready code.
Table of Contents
1. Setting Up a Spring Boot Project
Enable scheduling in your main class with @EnableScheduling
annonation.
Example:
@SpringBootApplication
@EnableScheduling
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
2. Basic Scheduled Task Example
Use the @Scheduled annotation to run tasks at fixed intervals:
@Service
public class ReportGenerator {
// Run every 5 seconds
@Scheduled(fixedRate = 5000)
public void generateReport() {
System.out.println("Report generated at: " + new Date());
}
// Delay 2 seconds between executions
@Scheduled(fixedDelay = 2000)
public void sendNotifications() {
System.out.println("Notifications sent at: " + new Date());
}
}
fixedDelay vs fixedRate
- fixedRate: Runs every N milliseconds regardless of previous execution time.
- fixedDelay: Waits N milliseconds after the previous task finishes.
3. Cron Jobs in Spring Boot
Define complex schedules using cron expressions:
@Scheduled(cron = "0 0 8 * * MON-FRI") // Runs at 8 AM on weekdays
public void dailyDatabaseBackup() {
System.out.println("Database backup completed.");
}
Common Cron Patterns:
Expression | Description |
---|---|
0 * * * * * | Every minute |
0 0/15 * * * * | Every 15 minutes |
0 0 12 * * ? | Noon daily |
4. Best Practices for Spring Boot Scheduled Tasks
4.1. Thread Pool Configuration
Avoid overlapping executions by configuring a custom thread pool:
@Configuration
public class SchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler threadPool = new ThreadPoolTaskScheduler();
threadPool.setPoolSize(5);
threadPool.setThreadNamePrefix("scheduled-task-");
threadPool.initialize();
taskRegistrar.setTaskScheduler(threadPool);
}
}
Detail explanation on Spring Boot Thread Pool Configuration
4.2. Error Handling
Wrap tasks in try-catch blocks to prevent silent failures:
@Scheduled(fixedRate = 10000)
public void fetchApiData() {
try {
// Call external API
} catch (Exception e) {
logger.error("API fetch failed: ", e);
}
}
5. Common Issues and Fixes
5.1. Overlapping Executions
Use fixedDelay
instead of fixedRate
for long-running tasks:
@Scheduled(fixedDelay = 30000) // Waits 30s after last execution
public void processLargeFile() {
// Time-consuming task
}
5.2. Time Zone Configuration
Specify time zones for cron jobs:
@Scheduled(cron = "0 0 12 * * ?", zone = "Europe/Paris")
public void timeZoneTask() {
// Runs at noon Paris time
}
6. Advanced: Dynamic Scheduling
Programmatically update tasks at runtime using ScheduledTaskRegistrar
:
@Autowired
private ScheduledTaskRegistrar taskRegistrar;
public void addDynamicTask(Runnable task, String cron) {
taskRegistrar.addCronTask(new CronTask(task, cron));
}
Conclusion
Mastering Spring Boot Scheduled Tasks empowers you to automate workflows efficiently. By leveraging the @Scheduled
annotation, cron jobs, and thread pool tuning, you can build resilient and scalable applications. Experiment with the code examples above, and explore advanced use cases like dynamic scheduling.