SpringBoot動(dòng)態(tài)定時(shí)任務(wù)實(shí)現(xiàn)完整版
本文定時(shí)任務(wù)功能(增、刪、改、啟動(dòng)、暫停) 話不多說,直接上代碼,你們直接CV就可以用?。?!
執(zhí)行定時(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; @Configuration public class SchedulingConfig { @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); // 定時(shí)任務(wù)執(zhí)行線程池核心線程數(shù) taskScheduler.setPoolSize(6); taskScheduler.setRemoveOnCancelPolicy(true); taskScheduler.setThreadNamePrefix("TaskSchedulerThreadPool-"); return taskScheduler; } }
ScheduledFuture的包裝類
ScheduledFuture是ScheduledExecutorService定時(shí)任務(wù)線程池的執(zhí)行結(jié)果。
import java.util.concurrent.ScheduledFuture; public final class ScheduledTask { volatile ScheduledFuture<?> future; /** * 取消定時(shí)任務(wù) */ public void cancel() { ScheduledFuture<?> future = this.future; if (future != null) { future.cancel(true); } } }
Runnable接口實(shí)現(xiàn)類
被定時(shí)任務(wù)線程池調(diào)用,用來執(zhí)行指定bean里面的方法。
import com.ying.demo.utils.springContextUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import java.lang.reflect.Method; import java.util.Objects; public class SchedulingRunnable implements Runnable { private static final Logger logger = LoggerFactory.getLogger(SchedulingRunnable.class); private String beanName; private String methodName; 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() { logger.info("定時(shí)任務(wù)開始執(zhí)行 - bean:{},方法:{},參數(shù):{}", beanName, methodName, params); long startTime = System.currentTimeMillis(); try { Object target = springContextUtils.getBean(beanName); Method method = null; if (!StringUtils.isEmpty(params)) { method = target.getClass().getDeclaredMethod(methodName, String.class); } else { method = target.getClass().getDeclaredMethod(methodName); } ReflectionUtils.makeAccessible(method); if (!StringUtils.isEmpty(params)) { method.invoke(target, params); } else { method.invoke(target); } } catch (Exception ex) { logger.error(String.format("定時(shí)任務(wù)執(zhí)行異常 - bean:%s,方法:%s,參數(shù):%s ", beanName, methodName, params), ex); } long times = System.currentTimeMillis() - startTime; logger.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); } }
定時(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; } public void addCronTask(Runnable task, String cronExpression) { addCronTask(new CronTask(task, cronExpression)); } 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)); } } 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(); } }
定時(shí)任務(wù)示例類
@Slf4j @Component("taskDemo") public class Task1 { public void taskByParams(String params) { log.info("taskByParams執(zhí)行時(shí)間:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.info("taskByParams執(zhí)行有參示例任務(wù):{}",params); } public void taskNoParams() { log.info("taskByParams執(zhí)行時(shí)間:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.info("taskNoParams執(zhí)行無參示例任務(wù)"); } public void test(String params) { log.info("test執(zhí)行時(shí)間:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.info("test執(zhí)行有參示例任務(wù):{}",params); } }
數(shù)據(jù)庫表設(shè)計(jì)
CREATE TABLE `schedule_setting` ( `job_id` int NOT NULL AUTO_INCREMENT COMMENT '任務(wù)ID', `bean_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'bean名稱', `method_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法名稱', `method_params` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '方法參數(shù)', `cron_expression` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'cron表達(dá)式', `remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '備注', `job_status` int DEFAULT NULL COMMENT '狀態(tài)(1正常 0暫停)', `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間', `update_time` datetime DEFAULT NULL COMMENT '修改時(shí)間', PRIMARY KEY (`job_id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
實(shí)體類
@Data public class ScheduleSetting extends Model<ScheduleSetting> { /** * 任務(wù)ID */ @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; }
定時(shí)任務(wù)預(yù)熱
spring boot項(xiàng)目啟動(dòng)完成后,加載數(shù)據(jù)庫里狀態(tài)為正常的定時(shí)任務(wù)
@Service public class SysJobRunner implements CommandLineRunner { private static final Logger logger = LoggerFactory.getLogger(SysJobRunner.class); @Autowired private CronTaskRegistrar cronTaskRegistrar; @Override public void run(String... args) { // 初始加載數(shù)據(jù)庫里狀態(tài)為正常的定時(shí)任務(wù) ScheduleSetting existedSysJob = new ScheduleSetting(); List<ScheduleSetting> jobList = existedSysJob.selectList(new QueryWrapper<ScheduleSetting>().eq("job_status", 1)); if (CollectionUtils.isNotEmpty(jobList)) { for (ScheduleSetting job : jobList) { SchedulingRunnable task = new SchedulingRunnable(job.getBeanName(), job.getMethodName(), job.getMethodParams()); cronTaskRegistrar.addCronTask(task, job.getCronExpression()); } logger.info("定時(shí)任務(wù)已加載完畢..."); } } }
工具類
用來從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); } }
定時(shí)任務(wù)的:增/刪/改/啟動(dòng)/暫停
@RestController public class TestController { @Autowired private CronTaskRegistrar cronTaskRegistrar; /** * 添加定時(shí)任務(wù) * * @param sysJob * @return */ @PostMapping("add") public boolean add(@RequestBody ScheduleSetting sysJob) { sysJob.setCreateTime(new Date()); sysJob.setUpdateTime(new Date()); boolean insert = sysJob.insert(); if (!insert) { return false; }else { if (sysJob.getJobStatus().equals(1)) {// 添加成功,并且狀態(tài)是1,直接放入任務(wù)器 SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams()); cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression()); } } return insert; } /** * 修改定時(shí)任務(wù) * * @param sysJob * @return */ @PostMapping("update") public boolean update(@RequestBody ScheduleSetting sysJob) { sysJob.setCreateTime(new Date()); sysJob.setUpdateTime(new Date()); // 查詢修改前任務(wù) ScheduleSetting existedSysJob = new ScheduleSetting(); existedSysJob = existedSysJob.selectOne(new QueryWrapper<ScheduleSetting>().eq("job_id", sysJob.getJobId())); // 修改任務(wù) boolean update = sysJob.update(new UpdateWrapper<ScheduleSetting>().eq("job_id", sysJob.getJobId())); if (!update) { return false; } else { // 修改成功,則先刪除任務(wù)器中的任務(wù),并重新添加 SchedulingRunnable task1 = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams()); cronTaskRegistrar.removeCronTask(task1); if (sysJob.getJobStatus().equals(1)) {// 如果修改后的任務(wù)狀態(tài)是1就加入任務(wù)器 SchedulingRunnable task = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams()); cronTaskRegistrar.addCronTask(task, sysJob.getCronExpression()); } } return update; } /** * 刪除任務(wù) * * @param jobId * @return */ @PostMapping("del/{jobId}") public boolean del(@PathVariable("jobId") Integer jobId) { // 先查詢要?jiǎng)h除的任務(wù)信息 ScheduleSetting existedSysJob = new ScheduleSetting(); existedSysJob = existedSysJob.selectOne(new QueryWrapper<ScheduleSetting>().eq("job_id", jobId)); // 刪除 boolean del = existedSysJob.delete(new QueryWrapper<ScheduleSetting>().eq("job_id", jobId)); if (!del) return false; else {// 刪除成功時(shí)要清除定時(shí)任務(wù)器中的對應(yīng)任務(wù) SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams()); cronTaskRegistrar.removeCronTask(task); } return del; } // 停止/啟動(dòng)任務(wù) @PostMapping("changesStatus/{jobId}/{stop}") public boolean changesStatus(@PathVariable("jobId") Integer jobId, @PathVariable("stop") Integer stop) { // 修改任務(wù)狀態(tài) ScheduleSetting scheduleSetting = new ScheduleSetting(); scheduleSetting.setJobStatus(stop); boolean job_id = scheduleSetting.update(new UpdateWrapper<ScheduleSetting>().eq("job_id", jobId)); if (!job_id) { return false; } // 查詢修改后的任務(wù)信息 ScheduleSetting existedSysJob = new ScheduleSetting(); existedSysJob = existedSysJob.selectOne(new QueryWrapper<ScheduleSetting>().eq("job_id", jobId)); // 如果狀態(tài)是1則添加任務(wù) if (existedSysJob.getJobStatus().equals(1)) { SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams()); cronTaskRegistrar.addCronTask(task, existedSysJob.getCronExpression()); } else { // 否則清除任務(wù) SchedulingRunnable task = new SchedulingRunnable(existedSysJob.getBeanName(), existedSysJob.getMethodName(), existedSysJob.getMethodParams()); cronTaskRegistrar.removeCronTask(task); } return true; }
cron
cron表達(dá)式語法:
[秒] [分] [小時(shí)] [日] [月] [周] [年]
注:[年]不是必須的域,可以省略[年],則一共6個(gè)域
通配符說明:
- * 表示所有值。 例如:在分的字段上設(shè)置 *,表示每一分鐘都會(huì)觸發(fā)。
- ? 表示不指定值。使用的場景為不需要關(guān)心當(dāng)前設(shè)置這個(gè)字段的值。例如:要在每月的10號(hào)觸發(fā)一個(gè)操作,但不關(guān)心是周幾,所以需要周位置的那個(gè)字段設(shè)置為”?” 具體設(shè)置為 0 0 0 10 * ?
- - 表示區(qū)間。例如 在小時(shí)上設(shè)置 “10-12”,表示 10,11,12點(diǎn)都會(huì)觸發(fā)。
- , 表示指定多個(gè)值,例如在周字段上設(shè)置 “MON,WED,FRI” 表示周一,周三和周五觸發(fā)
- / 用于遞增觸發(fā)。如在秒上面設(shè)置”5/15” 表示從5秒開始,每增15秒觸發(fā)(5,20,35,50)。 在日字段上設(shè)置’1/3’所示每月1號(hào)開始,每隔三天觸發(fā)一次。
- L 表示最后的意思。在日字段設(shè)置上,表示當(dāng)月的最后一天(依據(jù)當(dāng)前月份,如果是二月還會(huì)依據(jù)是否是潤年[leap]), 在周字段上表示星期六,相當(dāng)于”7”或”SAT”。如果在”L”前加上數(shù)字,則表示該數(shù)據(jù)的最后一個(gè)。例如在周字段上設(shè)置”6L”這樣的格式,則表示“本月最后一個(gè)星期五”
- W 表示離指定日期的最近那個(gè)工作日(周一至周五). 例如在日字段上置”15W”,表示離每月15號(hào)最近的那個(gè)工作日觸發(fā)。如果15號(hào)正好是周六,則找最近的周五(14號(hào))觸發(fā), 如果15號(hào)是周未,則找最近的下周一(16號(hào))觸發(fā).如果15號(hào)正好在工作日(周一至周五),則就在該天觸發(fā)。如果指定格式為 “1W”,它則表示每月1號(hào)往后最近的工作日觸發(fā)。如果1號(hào)正是周六,則將在3號(hào)下周一觸發(fā)。(注,”W”前只能設(shè)置具體的數(shù)字,不允許區(qū)間”-“)。
- # 序號(hào)(表示每月的第幾個(gè)周幾),例如在周字段上設(shè)置”6#3”表示在每月的第三個(gè)周六.注意如果指定”#5”,正好第五周沒有周六,則不會(huì)觸發(fā)該配置(用在母親節(jié)和父親節(jié)再合適不過了) ;小提示:’L’和 ‘W’可以一組合使用。如果在日字段上設(shè)置”LW”,則表示在本月的最后一個(gè)工作日觸發(fā);周字段的設(shè)置,若使用英文字母是不區(qū)分大小寫的,即MON與mon相同。
示例:
每隔5秒執(zhí)行一次:*/5 * * * * ?
每隔1分鐘執(zhí)行一次:0 */1 * * * ?
每天23點(diǎn)執(zhí)行一次:0 0 23 * * ?
每天凌晨1點(diǎn)執(zhí)行一次:0 0 1 * * ?
每月1號(hào)凌晨1點(diǎn)執(zhí)行一次:0 0 1 1 * ?
每月最后一天23點(diǎn)執(zhí)行一次:0 0 23 L * ?
每周星期六凌晨1點(diǎn)實(shí)行一次:0 0 1 ? * L
在26分、29分、33分執(zhí)行一次:0 26,29,33 * * * ?
每天的0點(diǎn)、13點(diǎn)、18點(diǎn)、21點(diǎn)都執(zhí)行一次:0 0 0,13,18,21 * * ?
cron在線表達(dá)式生成器:http://tools.jb51.net/code/Quartz_Cron_create
這是小編在開發(fā)學(xué)習(xí)使用和總結(jié)的小Demo, 這中間或許也存在著不足,希望可以得到大家的理解和建議。
總結(jié)
到此這篇關(guān)于SpringBoot動(dòng)態(tài)定時(shí)任務(wù)實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot動(dòng)態(tài)定時(shí)任務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 詳解SpringBoot 創(chuàng)建定時(shí)任務(wù)(配合數(shù)據(jù)庫動(dòng)態(tài)執(zhí)行)
- SpringBoot實(shí)現(xiàn)動(dòng)態(tài)定時(shí)任務(wù)
- Springboot整個(gè)Quartz實(shí)現(xiàn)動(dòng)態(tài)定時(shí)任務(wù)的示例代碼
- springboot整合Quartz實(shí)現(xiàn)動(dòng)態(tài)配置定時(shí)任務(wù)的方法
- 淺談SpringBoot集成Quartz動(dòng)態(tài)定時(shí)任務(wù)
- 基于Springboot執(zhí)行多個(gè)定時(shí)任務(wù)并動(dòng)態(tài)獲取定時(shí)任務(wù)信息
- SpringBoot設(shè)置動(dòng)態(tài)定時(shí)任務(wù)的方法詳解
- SpringBoot實(shí)現(xiàn)動(dòng)態(tài)多線程并發(fā)定時(shí)任務(wù)
相關(guān)文章
Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄)
這篇文章主要介紹了Spring Boot 實(shí)現(xiàn)https ssl免密登錄(X.509 pki登錄),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01使用Java實(shí)現(xiàn)大小寫轉(zhuǎn)換實(shí)例代碼
最近在開發(fā)項(xiàng)目中遇到一個(gè)比較好用的方法,那就是對字符串中的字母大小進(jìn)行轉(zhuǎn)換,所以下面這篇文章主要給大家介紹了關(guān)于如何使用Java實(shí)現(xiàn)大小寫轉(zhuǎn)換的相關(guān)資料,需要的朋友可以參考下2022-06-06基于ZooKeeper實(shí)現(xiàn)隊(duì)列源碼
這篇文章主要介紹了基于ZooKeeper實(shí)現(xiàn)隊(duì)列源碼的相關(guān)內(nèi)容,包括其實(shí)現(xiàn)原理和應(yīng)用場景,以及對隊(duì)列的簡單介紹,具有一定參考價(jià)值,需要的朋友可以了解下。2017-09-09詳解通過maven運(yùn)行項(xiàng)目的兩種方式
這篇文章主要介紹了通過maven運(yùn)行項(xiàng)目的兩種方式,給大家提到了通過tomcat的方式來啟動(dòng)maven項(xiàng)目的方法,通過圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-12-12SpringBoot Java后端實(shí)現(xiàn)okhttp3超時(shí)設(shè)置的方法實(shí)例
Okhttp的使用沒有httpClient廣泛,網(wǎng)上關(guān)于Okhttp設(shè)置代理的方法很少,下面這篇文章主要給大家介紹了關(guān)于SpringBoot Java后端實(shí)現(xiàn)okhttp3超時(shí)設(shè)置的相關(guān)資料,需要的朋友可以參考下2021-10-10小米Java程序員第二輪面試10個(gè)問題 你是否會(huì)被刷掉?
小米Java程序員第二輪面試10個(gè)問題,你是否會(huì)被刷掉?掌握好基礎(chǔ)知識(shí),祝大家面試順利2017-11-11