SpringBoot动态配置定时任务cron(动态改变执行周期)
package model; public class SpringScheduledCron { private String cronId; private String cronKey; private String cronExpression; private String taskExplain; private String status; @Override public String toString() { return "SpringScheduledCron{" + "cronId=" + cronId + ", cronKey='" + cronKey + '\'' + ", cronExpression='" + cronExpression + '\'' + ", taskExplain='" + taskExplain + '\'' + ", status=" + status + '}'; } public String getCronId() { return cronId; } public void setCronId(String cronId) { this.cronId = cronId; } public String getCronKey() { return cronKey; } public void setCronKey(String cronKey) { this.cronKey = cronKey; } public String getCronExpression() { return cronExpression; } public void setCronExpression(String cronExpression) { this.cronExpression = cronExpression; } public String getTaskExplain() { return taskExplain; } public void setTaskExplain(String taskExplain) { this.taskExplain = taskExplain; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public SpringScheduledCron() { // TODO Auto-generated constructor stub } public SpringScheduledCron(String cronId, String cronKey, String cronExpression, String taskExplain, String status) { this.cronId = cronId; this.cronKey = cronKey; this.cronExpression = cronExpression; this.taskExplain = taskExplain; this.status = status; } }
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; @Component public class SpringScheduledCronRepository { static int i = 0; static { System.out.println("in=="+(i++)); } public SpringScheduledCron findByCronKey(String cronKey) { SpringScheduledCron cron = null; List<SpringScheduledCron> list = findAll(); for (SpringScheduledCron springScheduledCron : list) { if(springScheduledCron.getCronKey().equals(cronKey)) { cron = springScheduledCron; } } return cron; }; public List<SpringScheduledCron> findAll(){ List<SpringScheduledCron> list = new ArrayList<SpringScheduledCron>(); try { File cronFile = new File("./config/cron.txt"); FileReader in = new FileReader(cronFile); BufferedReader bufIn = new BufferedReader(in); // 替换 String line = null; while ((line = bufIn.readLine()) != null) { String[] ls = line.split("\\|"); if(ls.length == 5) { SpringScheduledCron cron = new SpringScheduledCron(ls[0],ls[1],ls[2],ls[3],ls[4]); list.add(cron); } } // 关闭 输入流 bufIn.close(); } catch (Throwable e) { System.out.println(e.getMessage()); } return list; }; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringUtils.context = applicationContext; } public static <T> T getBean(Class<T> clz) { return context.getBean(clz); } public static Object getBean(String name) { return context.getBean(name); } public ApplicationContext getApplicationContext() { return context; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import org.springframework.scheduling.support.CronTrigger; import org.springframework.util.Assert; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration public class ScheduledConfig implements SchedulingConfigurer { @Autowired private ApplicationContext context; @Autowired private SpringScheduledCronRepository cronRepository; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { for (SpringScheduledCron springScheduledCron : cronRepository.findAll()) { Class<?> clazz; Object task; try { clazz = Class.forName(springScheduledCron.getCronKey()); task = context.getBean(clazz); } catch (ClassNotFoundException e) { throw new IllegalArgumentException( "" + springScheduledCron.getCronKey() + "有误" , e); } catch (BeansException e) { throw new IllegalArgumentException(springScheduledCron.getCronKey() + "未纳入到spring管理" , e); } Assert.isAssignable(ScheduledOfTask. class , task.getClass(), "定时任务类必须实现ScheduledOfTask接口" ); // 可以通过改变数据进而实现动态改变执行周期 taskRegistrar.addTriggerTask(((Runnable) task), triggerContext -> { String cronExpression = cronRepository.findByCronKey(springScheduledCron.getCronKey()).getCronExpression(); return new CronTrigger(cronExpression).nextExecutionTime(triggerContext); } ); } } @Bean public Executor taskExecutor() { return Executors.newScheduledThreadPool( 10 ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public interface ScheduledOfTask extends Runnable { /** * 定时任务方法 */ void execute(); /** * 实现控制定时任务启用或禁用的功能 */ @Override default void run() { SpringScheduledCronRepository repository = SpringUtils.getBean(SpringScheduledCronRepository. class ); SpringScheduledCron scheduledCron = repository.findByCronKey( this .getClass().getName()); if ( "" .equals(scheduledCron.getStatus())) { return ; } execute(); } } @Component public class DynamicPrintTask implements ScheduledOfTask { private Logger logger = LoggerFactory.getLogger(getClass()); private int i; @Override public void execute() { logger.info( "thread id:{},DynamicPrintTask execute times:{}" , Thread.currentThread().getId(), ++i); } } |
1 | 1 |com.schedule.DynamicPrintTask|*/ 10 * * * * ?|5s执行一次| 1 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
2016-09-01 用SpringMvc实现Excel导出功能