SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的幾種方式
一、基于注解
這種方式很簡(jiǎn)單,主要就是先@EnableScheduling開(kāi)啟定時(shí)任務(wù)功能,然后在相應(yīng)的方法上添加@Scheduled()中間寫(xiě)上相應(yīng)的cron表達(dá)式即可。示例如下:
schedule.ScheduleTask:
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling //開(kāi)啟定時(shí)任務(wù)
public class ScheduleTask {
@Scheduled(cron = "0/5 * * * * ?") //定時(shí)任務(wù)注解+cron表達(dá)式
public void testScheduleTask() {
System.out.println("執(zhí)行定時(shí)任務(wù)" + LocalDateTime.now());
}
}Cron表達(dá)式參數(shù)參考:
- 秒(0~59) 例如0/5表示每5秒
- 分(0~59)
- 時(shí)(0~23)
- 日(0~31)的某天,需計(jì)算
- 月(0~11)
- 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
建議:直接在線生成Cron表達(dá)式比較方便:www.matools.com/cron/
@Scheduled:除了支持靈活的參數(shù)表達(dá)式cron之外,還支持 fixedDelay,fixedRate,initialDelay 這些延時(shí)性的操作。

啟動(dòng)測(cè)試就實(shí)現(xiàn)了基本的定時(shí)任務(wù)功能,但是如果我們修改了cron表達(dá)式,需要重啟整個(gè)應(yīng)用才能生效,不是很方便。想要實(shí)現(xiàn)修改cron表達(dá)式就生效就需要用到接口的方式來(lái)實(shí)現(xiàn)定時(shí)任務(wù)。
二、基于接口
接口的方式是我們把定時(shí)任務(wù)的信息放在數(shù)據(jù)庫(kù)中,程序從數(shù)據(jù)庫(kù)去拉取定時(shí)任務(wù)的信息如cron表達(dá)式來(lái)實(shí)現(xiàn)實(shí)時(shí)修改生效等功能。
1. 首先在數(shù)據(jù)庫(kù)中創(chuàng)建一張用來(lái)記錄定時(shí)任務(wù)的表
CREATE TABLE `scheduled`?( ? `id` bigint NOT NULL AUTO_INCREMENT, ? `name` varchar(255) NULL, ? `cron` varchar(255) NULL, ? PRIMARY KEY (`id`) ) INSERT INTO `mydb`.`scheduled` (`id`, `name`, `cron`) VALUES (1, '定時(shí)任務(wù)1', '0/6 * * * * ?')
2. 在項(xiàng)目中引入mabatis-plus和mysql相應(yīng)的依賴包
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.32</version> </dependency>
3. 在application.yml中進(jìn)行連接數(shù)據(jù)庫(kù)相應(yīng)配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?characterEncoding=utf-8&serverTimeZone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver4. 定義查詢cron表達(dá)式的mapper
mapper.CronMapper:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface CronMapper {
@Select("select cron from scheduled where id=#{id}")
String getCron(Long id);
}5. 實(shí)現(xiàn)定時(shí)任務(wù)
import com.jk.mapper.CronMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling //開(kāi)啟定時(shí)任務(wù)
public class ScheduleTask implements SchedulingConfigurer {
@Autowired
private CronMapper cronMapper;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.addTriggerTask(
//添加任務(wù)內(nèi)容
() -> process(),
//設(shè)置執(zhí)行的周期
triggerContext -> {
//查詢cron表達(dá)式
String cron = cronMapper.getCron(1L);
if (cron.isEmpty()) {
System.out.println("cron is null");
}
return new CronTrigger(cron).nextExecutionTime(triggerContext);
});
}
private void process() {
System.out.println("基于接口的定時(shí)任務(wù)");
}
}這種方式需要去實(shí)現(xiàn)SchedulingConfigurer接口并重寫(xiě)configureTasks方法,然后設(shè)置任務(wù)內(nèi)容和執(zhí)行周期等,啟動(dòng)測(cè)試就實(shí)現(xiàn)了基于接口的定時(shí)任務(wù),此時(shí)我們改動(dòng)數(shù)據(jù)庫(kù)里的cron表達(dá)式也會(huì)實(shí)時(shí)生效

三、多線程定時(shí)任務(wù)
但上面的方法定義的定時(shí)任務(wù)會(huì)有個(gè)問(wèn)題,就是如果我一個(gè)定時(shí)任務(wù)里面執(zhí)行了復(fù)雜邏輯,導(dǎo)致本身執(zhí)行花的時(shí)間就已經(jīng)超過(guò)了定時(shí)任務(wù)間隔的時(shí)間怎么辦呢?這時(shí)候定時(shí)任務(wù)的執(zhí)行就會(huì)出現(xiàn)一定的問(wèn)題,具體如下,我用線程睡眠的方式模擬處理復(fù)雜邏輯
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling //開(kāi)啟定時(shí)任務(wù)
public class ScheduleTask {
@Scheduled(cron = "0/5 * * * * ?") //定時(shí)任務(wù)注解+cron表達(dá)式
public void testScheduleTask1() throws InterruptedException {
System.out.println("執(zhí)行定時(shí)任務(wù)1 " + LocalDateTime.now());
Thread.sleep(10 * 1000);
}
@Scheduled(cron = "0/5 * * * * ?") //定時(shí)任務(wù)注解+cron表達(dá)式
public void testScheduleTask2() {
System.out.println("執(zhí)行定時(shí)任務(wù)2 " + LocalDateTime.now());
}
}
可以看到兩個(gè)任務(wù)的執(zhí)行時(shí)間都被影響了,和我們?cè)O(shè)置的5秒不對(duì)應(yīng)。此時(shí)就可以使用多線程定時(shí)任務(wù)
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling //開(kāi)啟定時(shí)任務(wù)
@EnableAsync //開(kāi)啟多線程
public class ScheduleTask {
@Scheduled(cron = "0/5 * * * * ?") //定時(shí)任務(wù)注解+cron表達(dá)式
@Async
public void testScheduleTask1() throws InterruptedException {
System.out.println("執(zhí)行定時(shí)任務(wù)1 " + LocalDateTime.now());
Thread.sleep(10 * 1000);
}
@Scheduled(cron = "0/5 * * * * ?") //定時(shí)任務(wù)注解+cron表達(dá)式
@Async
public void testScheduleTask2() {
System.out.println("執(zhí)行定時(shí)任務(wù)2 " + LocalDateTime.now());
}
}
這樣多線程的定時(shí)任務(wù)就實(shí)現(xiàn)了,每個(gè)定時(shí)任務(wù)之間不會(huì)互相影響,定時(shí)任務(wù)執(zhí)行時(shí)間太長(zhǎng)也不會(huì)影響。
這就是定時(shí)任務(wù)實(shí)現(xiàn)的幾種方式,對(duì)大家有幫助的話多多
點(diǎn)贊、收藏哦,感謝!
以上就是SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的幾種方式的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 定時(shí)任務(wù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot定時(shí)任務(wù)兩種(Spring Schedule 與 Quartz 整合 )實(shí)現(xiàn)方法
- SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的4種方式詳解
- SpringBoot2 task scheduler 定時(shí)任務(wù)調(diào)度器四種方式
- SpringBoot下使用定時(shí)任務(wù)的方式全揭秘(6種)
- SpringBoot實(shí)現(xiàn)固定和動(dòng)態(tài)定時(shí)任務(wù)的三種方法
- Springboot實(shí)現(xiàn)定時(shí)任務(wù)的4種方式舉例詳解
- SpringBoot實(shí)現(xiàn)定時(shí)任務(wù)的三種方式小結(jié)
- SpringBoot最新定時(shí)任務(wù)的7種實(shí)現(xiàn)方案
相關(guān)文章
MyBatis中使用分頁(yè)插件PageHelper實(shí)現(xiàn)分頁(yè)功能
分頁(yè)是經(jīng)常使用的功能,本文主要介紹了Mybatis中處理特殊SQL處理邏輯,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
java JTree JCheckBox樹(shù)復(fù)選框詳解
這篇文章主要為大家詳細(xì)介紹了java JTree JCheckBox樹(shù)復(fù)選框的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
java代碼實(shí)現(xiàn)mysql分表操作(用戶行為記錄)
這篇文章主要介紹了java代碼實(shí)現(xiàn)mysql分表操作(用戶行為記錄),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Java實(shí)現(xiàn)在Word模板指定位置添加二維碼并生成?PDF
在實(shí)際業(yè)務(wù)場(chǎng)景中,我們常常需要在?Word?模板的指定位置貼上二維碼,然后將其轉(zhuǎn)換為?PDF?電子憑證文檔,下面我們就來(lái)看看具體實(shí)現(xiàn)方法吧2025-02-02
在Java生產(chǎn)環(huán)境下進(jìn)行性能監(jiān)控與調(diào)優(yōu)的詳細(xì)過(guò)程
在Java生產(chǎn)環(huán)境下進(jìn)行性能監(jiān)控與調(diào)優(yōu)是一個(gè)復(fù)雜但重要的過(guò)程,它涉及到多個(gè)方面,包括代碼分析、JVM監(jiān)控、線程管理、垃圾收集優(yōu)化、內(nèi)存管理、數(shù)據(jù)庫(kù)交互等,下面我將提供一個(gè)詳細(xì)的概述和示例代碼,需要的朋友可以參考下2025-02-02

