前記: 之前看xxl-job源碼的時候,看xxl的定時任務處理很微妙,不僅僅用了大小線程池,還用了netty手寫了一個rpc框架作為模塊之間的調用現在看動態的加載定時任務的cron表達式挺好的,
唯一不足的是還可以優化,將第一次查詢的數據加入緩存,每次去查的時候需要手動的去控制cron表達式,並將表達式入庫,清除緩存並且重新加載。
記住:提高效率就要用緩存,用了自身或者外部緩存就必須考慮緩存的大小(數據量),避免系統數據量過大而導致內存不足。
使用SpringBoot創建定時任務非常簡單,目前主要有以下三種創建方式:
- 一、基於注解(@Scheduled)
- 二、基於接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是實際使用中我們往往想從數據庫中讀取指定時間來動態執行定時任務,這時候基於接口的定時任務就派上用場了。
- 三、基於注解設定多線程定時任務
-
一、靜態:基於注解
基於注解@Scheduled默認為單線程,開啟多個任務時,任務的執行時機會受上一個任務執行時間的影響。
1、創建定時器
使用SpringBoot基於注解來創建定時任務非常簡單,只需幾行代碼便可完成:
-
@Configuration //1.主要用於標記配置類,兼備Component的效果。 @EnableScheduling // 2.開啟定時任務 public class SaticScheduleTask { //3.添加定時任務 @Scheduled(cron = "0/5 * * * * ?") //或直接指定時間間隔,例如:5秒 //@Scheduled(fixedRate=5000) private void configureTasks() { System.err.println("執行靜態定時任務時間: " + LocalDateTime.now()); } }
Cron表達式參數分別表示:
- 秒(0~59) 例如0/5表示每5秒
- 分(0~59)
- 時(0~23)
- 日(0~31)的某天,需計算
- 月(0~11)
- 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持靈活的參數表達式cron之外,還支持簡單的延時操作,例如 fixedDelay ,fixedRate 填寫相應的毫秒數即可。
二、動態:基於接口
基於接口(SchedulingConfigurer)
1、導入依賴包:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.0.4.RELEASE</version> </parent> <dependencies> <dependency><!--添加Web依賴 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency><!--添加MySql依賴 --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency><!--添加Mybatis依賴 配置mybatis的一些初始化的東西--> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency><!-- 添加mybatis依賴 --> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> <scope>compile</scope> </dependency> </dependencies>
2、添加數據庫記錄:
開啟本地數據庫mysql,隨便打開查詢窗口,然后執行腳本內容,如下:
DROP DATABASE IF EXISTS `socks`; CREATE DATABASE `socks`; USE `SOCKS`; DROP TABLE IF EXISTS `cron`; CREATE TABLE `cron` ( `cron_id` varchar(30) NOT NULL PRIMARY KEY, `cron` varchar(30) NOT NULL ); INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');
然后在項目中的application.yml 添加數據源:
spring: datasource: url: jdbc:mysql://localhost:3306/socks username: root password: 123456
@Configuration //1.主要用於標記配置類,兼備Component的效果。 @EnableScheduling // 2.開啟定時任務 public class DynamicScheduleTask implements SchedulingConfigurer { @Mapper public interface CronMapper { @Select("select cron from cron limit 1") public String getCron(); } @Autowired //注入mapper @SuppressWarnings("all") CronMapper cronMapper; /** * 執行定時任務. */ @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.addTriggerTask( //1.添加任務內容(Runnable) () -> System.out.println("執行動態定時任務: " + LocalDateTime.now().toLocalTime()), //2.設置執行周期(Trigger) triggerContext -> { //2.1 從數據庫獲取執行周期 String cron = cronMapper.getCron(); //2.2 合法性校驗. if (StringUtils.isEmpty(cron)) { // Omitted Code .. } //2.3 返回執行周期(Date) return new CronTrigger(cron).nextExecutionTime(triggerContext); } ); } }
4、啟動測試
啟動應用后,查看控制台,打印時間是我們預期的每10秒一次:
然后打開Navicat ,將執行周期修改為每6秒執行一次,如圖:
查看控制台,發現執行周期已經改變,並且不需要我們重啟應用,十分方便。如圖:
注意: 如果在數據庫修改時格式出現錯誤,則定時任務會停止,即使重新修改正確;此時只能重新啟動項目才能恢復。
三、多線程定時任務
基於注解設定多線程定時任務
1、創建多線程定時任務
//@Component注解用於對那些比較中立的類進行注釋; //相對與在持久層、業務層和控制層分別采用 @Repository、@Service 和 @Controller 對分層中的類進行注釋 @Component @EnableScheduling // 1.開啟定時任務 @EnableAsync // 2.開啟多線程 public class MultithreadScheduleTask { @Async @Scheduled(fixedDelay = 1000) //間隔1秒 public void first() throws InterruptedException { System.out.println("第一個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName()); System.out.println(); Thread.sleep(1000 * 10); } @Async @Scheduled(fixedDelay = 2000) public void second() { System.out.println("第二個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName()); System.out.println(); } }
注: 這里的@Async注解很關鍵
2、啟動測試
啟動應用后,查看控制台:
注意:轉 https://www.mmzsblog.cn/articles/2019/08/08/1565247960802.html