文章目錄
- 一、基本使用
- 1、配置:@EnableScheduling
- 2、觸發器:@Scheduled
- 二、拓展
- 1、修改默認的線程池
- 2、springboot配置
- 三、源碼分析
- 參考資料
一、基本使用
1、配置:@EnableScheduling
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;@Configuration
// 可以省略
@EnableAsync
// 開啟定時任務
@EnableScheduling
public class SchedulingConfiguration {
}
2、觸發器:@Scheduled
注意:
1、要調度的方法必須有void返回,并且不能接受任何參數。
2、@Scheduled可用作可重復的注釋。如果在同一個方法上發現了幾個@Scheduled注解,那么它們中的每一個都將被獨立處理,并為它們中的每一個觸發一個單獨的觸發器。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;import java.util.concurrent.TimeUnit;@Configuration
@EnableAsync
@EnableScheduling
public class SchedulingConfiguration {/*** 上一次調用結束和下一次調用開始之間的固定時間內執行* 也可以指定時間類型,默認是毫秒* @Scheduled(fixedDelay = 5, timeUnit = TimeUnit.SECONDS)*/@Scheduled(fixedDelay = 5000)public void doSomething() {System.out.println("每5秒觸發一次");}/*** 以固定的時間間隔執行*/@Scheduled(fixedRate = 5, timeUnit = TimeUnit.SECONDS)public void doSomething2() {System.out.println("每5秒執行一次2");}/*** 第一次延遲1秒執行,之后每隔5秒執行一次*/@Scheduled(initialDelay = 1000, fixedRate = 5000)public void doSomething3() {// something that should run periodically}/*** 延遲1秒執行,一次性任務*/@Scheduled(initialDelay = 1000)public void doSomething4() {// something that should run only once}/*** cron表達式*/@Scheduled(cron="*/5 * * * * MON-FRI")public void doSomething5() {// something that should run on weekdays only}}
二、拓展
1、修改默認的線程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;@Configuration
public class TaskSchedulerConfig {// bean名稱一定要是taskScheduler@Beanpublic ThreadPoolTaskScheduler taskScheduler() {ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();// 設置線程池大小scheduler.setPoolSize(5); // 設置線程名稱前綴scheduler.setThreadNamePrefix("my-scheduler-"); // 設置任務拒絕策略scheduler.setRejectedExecutionHandler((r, executor) -> {System.err.println("Task " + r.toString() + " rejected from " + executor.toString());});// 初始化調度器scheduler.initialize(); return scheduler;}
}
2、springboot配置
springboot的配置:修改線程池大小等
spring.task.scheduling.pool.size=5
spring.task.scheduling.thread-name-prefix=config-scheduler-
三、源碼分析
springboot默認會自動配置,創建一個ThreadPoolTaskScheduler:
但是默認的線程池的PoolSize是1
!!!這是個坑,需要注意。
參考資料
https://docs.spring.io/spring-framework/reference/integration/scheduling.html