SpringBoot設(shè)置動態(tài)定時任務的方法詳解
之前寫過文章記錄怎么在SpringBoot項目中簡單使用定時任務,不過由于要借助cron表達式且都提前定義好放在配置文件里,不能在項目運行中動態(tài)修改任務執(zhí)行時間,實在不太靈活。
經(jīng)過網(wǎng)上搜索學習后,特此記錄如何在SpringBoot項目中實現(xiàn)動態(tài)定時任務。
因為只是一個demo,所以只引入了需要的依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
<optional>true</optional>
</dependency>
<!-- spring boot 2.3版本后,如果需要使用校驗,需手動導入validation包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>啟動類:
package com.wl.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* @author wl
* @date 2022/3/22
*/
@EnableScheduling
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("(*^▽^*)啟動成功!!!(〃'▽'〃)");
}
}配置文件application.yml,只定義了服務端口:
server: port: 8089
定時任務執(zhí)行時間配置文件:task-config.ini:
printTime.cron=0/10 * * * * ?
定時任務執(zhí)行類:
package com.wl.demo.task;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 定時任務
* @author wl
* @date 2022/3/22
*/
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
public class ScheduleTask implements SchedulingConfigurer {
@Value("${printTime.cron}")
private String cron;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 動態(tài)使用cron表達式設(shè)置循環(huán)間隔
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
log.info("Current time: {}", LocalDateTime.now());
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 使用CronTrigger觸發(fā)器,可動態(tài)修改cron表達式來操作循環(huán)規(guī)則
CronTrigger cronTrigger = new CronTrigger(cron);
Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
return nextExecutionTime;
}
});
}
}編寫一個接口,使得可以通過調(diào)用接口動態(tài)修改該定時任務的執(zhí)行時間:
package com.wl.demo.controller;
import com.wl.demo.task.ScheduleTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wl
* @date 2022/3/22
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
private final ScheduleTask scheduleTask;
@Autowired
public TestController(ScheduleTask scheduleTask) {
this.scheduleTask = scheduleTask;
}
@GetMapping("/updateCron")
public String updateCron(String cron) {
log.info("new cron :{}", cron);
scheduleTask.setCron(cron);
return "ok";
}
}啟動項目,可以看到任務每10秒執(zhí)行一次:

訪問接口,傳入請求參數(shù)cron表達式,將定時任務修改為15秒執(zhí)行一次:

可以看到任務變成了15秒執(zhí)行一次

除了上面的借助cron表達式的方法,還有另一種觸發(fā)器,區(qū)別于CronTrigger觸發(fā)器,該觸發(fā)器可隨意設(shè)置循環(huán)間隔時間,不像cron表達式只能定義小于等于間隔59秒。
package com.wl.demo.task;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 定時任務
* @author wl
* @date 2022/3/22
*/
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
public class ScheduleTask implements SchedulingConfigurer {
@Value("${printTime.cron}")
private String cron;
private Long timer = 10000L;
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
// 動態(tài)使用cron表達式設(shè)置循環(huán)間隔
taskRegistrar.addTriggerTask(new Runnable() {
@Override
public void run() {
log.info("Current time: {}", LocalDateTime.now());
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 使用CronTrigger觸發(fā)器,可動態(tài)修改cron表達式來操作循環(huán)規(guī)則
// CronTrigger cronTrigger = new CronTrigger(cron);
// Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);
// 使用不同的觸發(fā)器,為設(shè)置循環(huán)時間的關(guān)鍵,區(qū)別于CronTrigger觸發(fā)器,該觸發(fā)器可隨意設(shè)置循環(huán)間隔時間,單位為毫秒
PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer);
Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext);
return nextExecutionTime;
}
});
}
}增加一個修改時間的接口:
package com.wl.demo.controller;
import com.wl.demo.task.ScheduleTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author wl
* @date 2022/3/22
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
private final ScheduleTask scheduleTask;
@Autowired
public TestController(ScheduleTask scheduleTask) {
this.scheduleTask = scheduleTask;
}
@GetMapping("/updateCron")
public String updateCron(String cron) {
log.info("new cron :{}", cron);
scheduleTask.setCron(cron);
return "ok";
}
@GetMapping("/updateTimer")
public String updateTimer(Long timer) {
log.info("new timer :{}", timer);
scheduleTask.setTimer(timer);
return "ok";
}
}測試結(jié)果:

到此這篇關(guān)于SpringBoot設(shè)置動態(tài)定時任務的方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot設(shè)置動態(tài)定時任務內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot實現(xiàn)動態(tài)定時任務
- SpringBoot 動態(tài)定時器的使用方法
- 淺談SpringBoot集成Quartz動態(tài)定時任務
- SpringBoot實現(xiàn)固定和動態(tài)定時任務的三種方法
- SpringBoot實現(xiàn)設(shè)置動態(tài)定時任務的方法詳解
- SpringBoot創(chuàng)建動態(tài)定時任務的幾種方式小結(jié)
- SpringBoot+Quartz實現(xiàn)動態(tài)定時任務
- Springboot實現(xiàn)動態(tài)定時任務流程詳解
- SpringBoot動態(tài)定時任務實現(xiàn)完整版
- Springboot實現(xiàn)動態(tài)定時任務管理的示例代碼
- 基于Nacos實現(xiàn)SpringBoot動態(tài)定時任務調(diào)度
相關(guān)文章
Spring Boot項目添加外部Jar包以及配置多數(shù)據(jù)源的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring Boot項目添加外部Jar包以及配置多數(shù)據(jù)源的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-06-06
Java中Cookie和Session詳解及區(qū)別總結(jié)
這篇文章主要介紹了Java中Cookie和Session詳解,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-06-06
Java修飾符abstract與static及final的精華總結(jié)
abstract、static、final三個修飾符是經(jīng)常會使用的,對他們的概念必須非常清楚,弄混了會產(chǎn)生些完全可以避免的錯誤,比如final和abstract不能一同出現(xiàn),static和abstract不能一同出現(xiàn),下面我們來詳細了解2022-04-04
SpringAOP 構(gòu)造注入的實現(xiàn)步驟
這篇文章主要介紹了SpringAOP_構(gòu)造注入的實現(xiàn)步驟,幫助大家更好的理解和學習使用spring框架,感興趣的朋友可以了解下2021-05-05

