Code ví dụ Spring Boot tạo lịch với annotation @Scheduled.
(Xem lại: Hướng dẫn tạo lịch (Task, Scheduler) với @Schedule trong Spring)
Các công nghệ sử dụng:
Tạo Spring Boot Project
Không cần chọn thêm thư viện nào cả.
Cấu trúc Project
File main chạy ứng dụng:
package stackjava.com.sbschedule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@SpringBootApplication
@EnableScheduling
public class SpringBootScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootScheduleApplication.class, args);
}
@Bean
public TaskScheduler taskScheduler() {
final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10);
return scheduler;
}
}
- Annotation
@EnableSchedulingbật tính năng Schedule cho Spring - Bean
TaskSchedulerthiết lập các thông số cho tính năng schedule (ở đây mình thiết lập poolsize = 10)
File MyJob.java chứa các method chạy theo lịch
package stackjava.com.sbschedule.job;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyJob {
@Scheduled(fixedDelay = 1000)
public void scheduleFixedDelayTask() throws InterruptedException {
System.out.println("Task1 - " + new Date());
}
@Scheduled(fixedRate = 2000)
public void scheduleFixedRateTask() throws InterruptedException {
System.out.println("Task2 - " + new Date());
}
@Scheduled(cron = "*/3 * * * * *")
public void scheduleTaskUsingCronExpression() throws InterruptedException {
System.out.println("Task3 - " + new Date());
}
}
- Method
scheduleFixedDelayTaskcứ 1 giậy lặp lại một lần - Method
scheduleFixedRateTaskcứ 2 giây lặp lại một lần - Method
scheduleTaskUsingCronExpressioncứ 3 giây lặp lại một lần
(Xem lại bài Hướng dẫn tạo lịch (Task, Scheduler) với @Schedule trong Spring để hiểu rõ cơ chế tạo schedule với fixedRate, fixedDelay hay cron)
Demo
Cứ 1 giây method scheduleFixedDelayTask lại in ra thời gian hiện tại một lần
Cứ 2 giây method scheduleFixedRateTask lại in ra thời gian hiện tại một lần
Cứ 3 giây method scheduleTaskUsingCronExpression lại in ra thời gian hiện tại một lần
Okay, Done!
Download code ví dụ trên tại đây
References:






