springboot使用Scheduling實(shí)現(xiàn)動(dòng)態(tài)增刪啟停定時(shí)任務(wù)教程
在項(xiàng)目開發(fā)過程中,如果是一些簡單的工程,非分布式工程,一般我們可以使用@EnableScheduling注解和@Scheduled注解實(shí)現(xiàn)簡單的定時(shí)任務(wù),也可以使用SchedulingConfigurer接口來實(shí)現(xiàn)定時(shí)任務(wù)。那如何動(dòng)態(tài)的來生成定時(shí)任務(wù)呢?
下面是具體步驟,可以結(jié)合數(shù)據(jù)庫,來存儲(chǔ)定時(shí)任務(wù)所需要的參數(shù)數(shù)據(jù),如bean的名稱、方法名,方法參數(shù)、執(zhí)行的表達(dá)式等等。
1、配置定時(shí)任務(wù)需要的線程池
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
// 配置定時(shí)任務(wù)線程池
@Configuration
public class SchedulingConfig {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
// 定時(shí)任務(wù)執(zhí)行線程池核心線程數(shù)
taskScheduler.setPoolSize(4);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-test-");
return taskScheduler;
}
}2、創(chuàng)建ScheduledFuture的包裝類
// ScheduledFuture的包裝類
public final class ScheduledTask {
volatile ScheduledFuture<?> future;
/**
* 取消定時(shí)任務(wù)
*/
public void cancel() {
ScheduledFuture<?> future = this.future;
if (future != null) {
future.cancel(true);
}
}
}3、注冊定時(shí)任務(wù),增加、刪除任務(wù)
/**
* 添加定時(shí)任務(wù)注冊,用來增加、刪除定時(shí)任務(wù)。
*/
@Component
public class CronTaskRegistrar implements DisposableBean {
private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
@Autowired
private TaskScheduler taskScheduler;
public TaskScheduler getScheduler() {
return this.taskScheduler;
}
// 添加定時(shí)任務(wù)
public void addCronTask(Runnable task, String cronExpression) {
addCronTask(new CronTask(task, cronExpression));
}
// 添加定時(shí)任務(wù)
public void addCronTask(CronTask cronTask) {
if (cronTask != null) {
Runnable task = cronTask.getRunnable();
if (this.scheduledTasks.containsKey(task)) {
removeCronTask(task);
}
this.scheduledTasks.put(task, scheduleCronTask(cronTask));
}
}
// 移除定時(shí)任務(wù)
public void removeCronTask(Runnable task) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
if (scheduledTask != null)
scheduledTask.cancel();
}
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
return scheduledTask;
}
@Override
public void destroy() {
for (ScheduledTask task : this.scheduledTasks.values()) {
task.cancel();
}
this.scheduledTasks.clear();
}
}4、創(chuàng)建具體執(zhí)行bean中方法的類
// 添加Runnable接口實(shí)現(xiàn)類,被定時(shí)任務(wù)線程池調(diào)用,用來執(zhí)行指定bean里面的方法。
@Slf4j
public class SchedulingRunnable implements Runnable {
// bean名稱
private String beanName;
// 方法名稱
private String methodName;
// 方法參數(shù)
private String params;
public SchedulingRunnable(String beanName, String methodName) {
this(beanName, methodName, null);
}
public SchedulingRunnable(String beanName, String methodName, String params) {
this.beanName = beanName;
this.methodName = methodName;
this.params = params;
}
@Override
public void run() {
log.info("定時(shí)任務(wù)開始執(zhí)行 - bean:{},方法:{},參數(shù):{}", beanName, methodName, params);
long startTime = System.currentTimeMillis();
try {
Object target = SpringContextUtils.getBean(beanName);
Method method = null;
if (StringUtils.isNotEmpty(params)) {
method = target.getClass().getDeclaredMethod(methodName, String.class);
} else {
method = target.getClass().getDeclaredMethod(methodName);
}
ReflectionUtils.makeAccessible(method);
if (StringUtils.isNotEmpty(params)) {
method.invoke(target, params);
} else {
method.invoke(target);
}
} catch (Exception ex) {
log.error(String.format("定時(shí)任務(wù)執(zhí)行異常 - bean:%s,方法:%s,參數(shù):%s ", beanName, methodName, params), ex);
}
long times = System.currentTimeMillis() - startTime;
log.info("定時(shí)任務(wù)執(zhí)行結(jié)束 - bean:{},方法:{},參數(shù):{},耗時(shí):{} 毫秒", beanName, methodName, params, times);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SchedulingRunnable that = (SchedulingRunnable) o;
if (params == null) {
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
that.params == null;
}
return beanName.equals(that.beanName) &&
methodName.equals(that.methodName) &&
params.equals(that.params);
}
@Override
public int hashCode() {
if (params == null) {
return Objects.hash(beanName, methodName);
}
return Objects.hash(beanName, methodName, params);
}
}5、從spring容器里獲取bean
// 從spring容器里獲取bean
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
SpringContextUtils.applicationContext = applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
public static <T> T getBean(String name, Class<T> requiredType) {
return applicationContext.getBean(name, requiredType);
}
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
public static boolean isSingleton(String name) {
return applicationContext.isSingleton(name);
}
public static Class<? extends Object> getType(String name) {
return applicationContext.getType(name);
}
}6、創(chuàng)建具體執(zhí)行的bean以及方法
// 測試類
@Component("testTask")
public class TestTask {
/**
* 有參方法
* @param params
*/
public void taskWithParams(String params) {
System.out.println("執(zhí)行有參示例任務(wù):" + params);
}
/**
* 無慘方法
*/
public void taskNoParams() {
System.out.println("執(zhí)行無參示例任務(wù)");
}
}7、接口測試類
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private CronTaskRegistrar cronTaskRegistrar;
@RequestMapping("/addTest")
public String addTest(boolean flg){
SchedulingRunnable task;
if (flg) {
// 創(chuàng)建無慘任務(wù)
task = new SchedulingRunnable("testTask", "taskNoParams");
}
else {
task = new SchedulingRunnable("testTask", "taskWithParams", "hello word");
}
cronTaskRegistrar.addCronTask(task, "0/1 * * * * *");
return "ok";
}
@RequestMapping("/updateTest")
public String updateTest(boolean flg){
//先移除再添加
if(flg) {
// 創(chuàng)建無慘任務(wù)
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskNoParams");
cronTaskRegistrar.removeCronTask(task);
}
else {
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskWithParams", "hello word");
cronTaskRegistrar.removeCronTask(task);
}
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskWithParams", "hello word");
cronTaskRegistrar.addCronTask(task, "0/5 * * * * *");
return "ok";
}
@RequestMapping("/delTest")
public String delTest(){
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskNoParams");
cronTaskRegistrar.removeCronTask(task);
return "ok";
}
@RequestMapping("/startTest")
public String startTest(boolean flg){
/**
* 啟停定時(shí)任務(wù)的邏輯就是創(chuàng)建新的任務(wù)或者刪除任務(wù),參數(shù)一致即可
* 可以結(jié)合數(shù)據(jù)庫,將配置信息存入數(shù)據(jù)庫
*/
if(flg) {
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskNoParams");
cronTaskRegistrar.addCronTask(task, "0/5 * * * * *");
}
else {
SchedulingRunnable task = new SchedulingRunnable("testTask", "taskNoParams");
cronTaskRegistrar.removeCronTask(task);
}
return "ok";
}
}8、結(jié)合數(shù)據(jù)庫,創(chuàng)建對(duì)應(yīng)的實(shí)體
// 定時(shí)任務(wù)實(shí)體
@Data
public class JobEntity {
/**
* 任務(wù)ID
*/
private Integer jobId;
/**
* bean名稱
*/
private String beanName;
/**
* 方法名稱
*/
private String methodName;
/**
* 方法參數(shù)
*/
private String methodParams;
/**
* cron表達(dá)式
*/
private String cronExpression;
/**
* 狀態(tài)(1正常 0暫停)
*/
private Integer jobStatus;
/**
* 備注
*/
private String remark;
/**
* 創(chuàng)建時(shí)間
*/
private Date createTime;
/**
* 更新時(shí)間
*/
private Date updateTime;
}9、讀取數(shù)據(jù)庫要執(zhí)行的任務(wù)
在程序啟動(dòng)的時(shí)候,讀取數(shù)據(jù)庫,并創(chuàng)建要執(zhí)行任務(wù)
/**
* @description: 初始化數(shù)據(jù)庫任務(wù),可以再程啟動(dòng)的時(shí)候加載數(shù)據(jù)庫里的任務(wù)
* @author: HK
* @since: 2025/4/21 18:21
*/
@Component
@Slf4j
public class InitTask implements CommandLineRunner {
@Autowired
private CronTaskRegistrar cronTaskRegistrar;
@Override
public void run(String... args) {
// 初始加載數(shù)據(jù)庫里狀態(tài)為正常的定時(shí)任務(wù)
/* List<SysJobPO> jobList = service.getJobList("1");
if (CollectionUtils.isNotEmpty(jobList)) {
for (SysJobPO job : jobList) {
SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams());
cronTaskRegistrar.addCronTask(task, job.getCronExpression());
}
log.info("定時(shí)任務(wù)已加載完畢...");
}*/
}
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- springboot定時(shí)任務(wù)SchedulingConfigurer異步多線程實(shí)現(xiàn)方式
- SpringBoot注解@EnableScheduling定時(shí)任務(wù)詳細(xì)解析
- SpringBoot使用Scheduling實(shí)現(xiàn)定時(shí)任務(wù)的示例代碼
- springboot通過SchedulingConfigurer實(shí)現(xiàn)多定時(shí)任務(wù)注冊及動(dòng)態(tài)修改執(zhí)行周期(示例詳解)
- springboot項(xiàng)目使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)的案例代碼
- SpringBoot使用SchedulingConfigurer實(shí)現(xiàn)多個(gè)定時(shí)任務(wù)多機(jī)器部署問題(推薦)
- SpringBoot Scheduling定時(shí)任務(wù)的示例代碼
相關(guān)文章
JAVA如何判斷上傳文件后綴名是否符合規(guī)范MultipartFile
這篇文章主要介紹了JAVA判斷上傳文件后綴名是否符合規(guī)范MultipartFile,文中通過實(shí)例代碼介紹了java實(shí)現(xiàn)對(duì)上傳文件做安全性檢查,需要的朋友可以參考下2023-11-11
Java接口返回省市區(qū)樹形結(jié)構(gòu)的實(shí)現(xiàn)
本文主要介紹了Java接口返回省市區(qū)樹形結(jié)構(gòu)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
IntelliJ IDEA 安裝及初次使用圖文教程(2020.3.2社區(qū)版)
這篇文章主要介紹了IntelliJ IDEA 安裝及初次使用(2020.3.2社區(qū)版),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
java JVM原理與常識(shí)知識(shí)點(diǎn)
在本文中小編給大家分享的是關(guān)于java的JVM原理和java常識(shí),有興趣的朋友們可以學(xué)習(xí)下2018-12-12
Java Web項(xiàng)目中編寫定時(shí)任務(wù)的實(shí)現(xiàn)
本篇文章主要介紹了Java Web項(xiàng)目中編寫定時(shí)任務(wù)的實(shí)現(xiàn),具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01

