@Scheduled chạy method theo lịch định kỳ — cron job, background task.
@SpringBootApplication
@EnableScheduling
class App {}
@Component
class ScheduledTasks {
// Mỗi 5 phút
@Scheduled(fixedRate = 300_000)
void syncExchangeRate() {
rateService.fetchAndUpdate();
}
// 30 giây sau khi method trước hoàn thành
@Scheduled(fixedDelay = 30_000)
void cleanupTempFiles() {
fileService.cleanup();
}
// Cron: mỗi ngày 2h sáng
@Scheduled(cron = "0 0 2 * * *")
void dailyReport() {
reportService.generate();
}
// Cron với timezone
@Scheduled(cron = "0 0 8 * * MON-FRI", zone = "Asia/Ho_Chi_Minh")
void morningDigest() {
mailService.sendDigest();
}
}Cron format (Spring — 6 field, khác Unix chuẩn 5 field): {giây} {phút} {giờ} {ngày} {tháng} {thứ}
Lưu ý quan trọng: @Scheduled chạy trên single thread mặc định → tasks xếp hàng chờ nhau. Config thread pool:
@Bean
TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
return scheduler;
}Multiple instance: @Scheduled chạy trên mọi instance → duplicate job.
Fix: Spring Batch / Quartz với DB-level lock, hoặc ShedLock library.
@Scheduled runs methods on a schedule — cron jobs, background tasks.
@SpringBootApplication
@EnableScheduling
class App {}
@Component
class ScheduledTasks {
// Every 5 minutes
@Scheduled(fixedRate = 300_000)
void syncExchangeRate() {
rateService.fetchAndUpdate();
}
// 30 seconds after the previous invocation completes
@Scheduled(fixedDelay = 30_000)
void cleanupTempFiles() {
fileService.cleanup();
}
// Cron: daily at 2am
@Scheduled(cron = "0 0 2 * * *")
void dailyReport() {
reportService.generate();
}
// Cron with timezone
@Scheduled(cron = "0 0 8 * * MON-FRI", zone = "Asia/Ho_Chi_Minh")
void morningDigest() {
mailService.sendDigest();
}
}Cron format (Spring — 6 fields, unlike standard Unix cron with 5): {seconds} {minutes} {hours} {day} {month} {day-of-week}
Important note: @Scheduled runs on a single thread by default → tasks queue up. Configure a thread pool:
@Bean
TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
return scheduler;
}Multiple instances: @Scheduled runs on every instance → duplicate jobs.
Fix: Spring Batch/Quartz with DB-level locking, or the ShedLock library.