springboot Scheduled定時器 單線程多線程實現
springboot單線程定時任務很簡單:
1. 在項目啓動類上加@EnableScheduling註解
只有加了這個註解,才能掃描到@Scheduled註解, 定時器纔會起作用
@SpringBootApplication
@EnableScheduling//允許使用定時器
public class SpringbootScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootScheduledApplication.class, args);
}
}
2.定義一個類,加@competition,類中的方法加@Scheduled註解,定時器就定義好了
@competition,將該類加入springboot 的 been 中,是spring可以掃描到該類
@Scheduled(cron="*****?") cron表達式,指定任務在特定時間執行;
@Scheduled(fixedRate=1000 * 60 *60 ) 從第一次開始執行算起, 1000 * 60 *60ms 後執行第二次;
@Scheduled(fixedDelay =1000 * 60 *60 ) 從第一次執行完算起, 1000 * 60 *60ms 後執行第二次;
@Component
public class SchedualedTask {
private Log log = LogFactory.getLog(SchedualedTask.class);
//定時器1.
// @Scheduled(fixedRate = 1000*60*60)
@Scheduled(fixedDelay = 1000*10)
public void task1(){
for (int i = 0; i < 100; i++) {
log.info("task1================================================================="+i);
}
}
//定時器2.
@Scheduled(fixedDelay = 1000*10)
public void task2(){
for (int i = 0; i < 100; i++) {
log.info("task2================================================================="+i);
}
}
}
運行結果,定時器1和2,單線程串行執行
如何實現多線程呢
1.在上面代碼的基礎上,重新定義一個類,實現 SchedulingConfigurer,在重寫的方法中,調用定時器任務註冊器scheduledTaskRegistrar,setScheduler() 傳入一個新的線程池,自己可以定義線程池的size. 默認的線城池爲SingleThreadScheduledExecutor,所以爲單線程
@Configuration
//定時任務調用一個線程池中的線程。
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
//參數傳入一個size爲10的線程池
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
}
}
這樣重新啓動項目,我們的定時任務就會多線程並行執行了.
附上簡單案例的代碼 GitHub https://github.com/nokekang/springboot-scheduled
希望對初學者有所幫助