網(wǎng)站首頁 編程語言 正文
SpringBoot創(chuàng)建定時任務,目前主要有以下三種實現(xiàn)方式:
一、基于注解(@Scheduled)
? 基于注解@Scheduled默認為單線程,開啟多個任務時,任務的執(zhí)行時機會受上一個任務執(zhí)行時間的影響;
二、基于接口(SchedulingConfigurer)
? 用于實現(xiàn)從數(shù)據(jù)庫獲取指定時間來動態(tài)執(zhí)行定時任務;
三、基于注解設定多線程定時任務
? 基于注解設定多線程定時任務;
一、靜態(tài):基于注解
使用SpringBoot基于注解來創(chuàng)建定時任務比較簡單,只需要如下代碼即可。 代碼如下:
@Configuration //1.主要用于標記配置類,兼?zhèn)銫omponent的效果。
@EnableScheduling // 2.開啟定時任務
public class SaticScheduleTask {
//3.添加定時任務
@Scheduled(cron = "0/5 * * * * ?")
//或直接指定時間間隔,例如:5秒
//@Scheduled(fixedRate=5000)
private void configureTasks() {
System.err.println("執(zhí)行靜態(tài)定時任務時間: " + LocalDateTime.now());
}
}
Cron表達式參數(shù)分別表示: 秒(0~59) 例如0/5表示每5秒 分(0~59) 時(0~23) 日(031)的某天,需計算月(011) 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持靈活的參數(shù)表達式cron之外,還支持簡單的延時操作,例如 fixedDelay ,fixedRate填寫相應的毫秒數(shù)即可。
建議:直接點擊在線Cron表達式生成器生成參數(shù)比較方便
啟動測試:
顯然,使用@Scheduled
注解很方便,但缺點是當我們調(diào)整了執(zhí)行周期的時候,需要重啟應用才能生效,這多少有些不方便。為了達到實時生效的效果,可以使用接口來完成定時任務。
二、動態(tài):基于接口
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、添加數(shù)據(jù)庫記錄:
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 * * * * ?');
3、創(chuàng)建定時器
數(shù)據(jù)庫準備好數(shù)據(jù)后,開始編寫定時任務,注意這里添加的是TriggerTask,目的是循環(huán)讀取我們在數(shù)據(jù)庫設置好的執(zhí)行周期,以及執(zhí)行相關定時任務的內(nèi)容,具體代碼如下:
@Configuration //1.主要用于標記配置類,兼?zhèn)銫omponent的效果。
@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;
/**
* 執(zhí)行定時任務.
*/
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//1.添加任務內(nèi)容(Runnable)
() -> System.out.println("執(zhí)行動態(tài)定時任務: " + LocalDateTime.now().toLocalTime()),
//2.設置執(zhí)行周期(Trigger)
triggerContext -> {
//2.1 從數(shù)據(jù)庫獲取執(zhí)行周期
String cron = cronMapper.getCron();
//2.2 合法性校驗.
if (StringUtils.isEmpty(cron)) {
// Omitted Code ..
}
//2.3 返回執(zhí)行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
三、多線程定時任務
1.創(chuàng)建多線程定時任務
//@Component注解用于對那些比較中立的類進行注釋;
//相對與在持久層、業(yè)務層和控制層分別采用 @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://blog.csdn.net/mcband/article/details/125590094
相關推薦
- 2022-08-01 Go語言上下文context底層原理_Golang
- 2022-04-09 使用docker-compose一鍵部署開源博客wordpress
- 2022-11-21 C++實現(xiàn)TCP客戶端及服務器Recv數(shù)據(jù)篩選處理詳解_C 語言
- 2022-03-14 surface屏幕自動調(diào)節(jié)亮度無法關閉
- 2022-07-03 C#并行編程之信號量_C#教程
- 2022-04-23 git如何提交本地倉庫并同步碼云倉庫
- 2022-06-28 python反轉(zhuǎn)單鏈表算法題_python
- 2022-03-27 Python函數(shù)的嵌套詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支