1、概述: 在开发中有的时候需要去手动禁止和启用定时任务,修改定时任务的cron表达式然后再让其动态生效,之前有过SSM的类似的业务的开发但是忘记写下来了。。。只好重新温习了一次,加上最近比较流行springBoot所以升级了一下用springBoot来完成.

成都创新互联公司-专业网站定制、快速模板网站建设、高性价比扎兰屯网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式扎兰屯网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖扎兰屯地区。费用合理售后完善,10年实体公司更值得信赖。
2、关联技术 SpringBoot、Quartz、H2、thymeleaf (好像就这么多)
3、具体流程
1)首先去手动创建一个调度器工厂对象-SchedulerFactoryBean;其实应该不用手动创建的但是为了顾及到业务的复杂性所以还是创建一个好用。
@Bean
public SchedulerFactoryBean schedulerFactory(){
SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
/*用于Quartz集群,启动时更新已存在的Job*/
factoryBean.setOverwriteExistingJobs(true);
/*定时任务开始启动后延迟5秒开始*/
factoryBean.setStartupDelay(5);
return factoryBean;
}
2)获取到
//得到调度器 Scheduler scheduler = schedulerFactoryBean.getScheduler();
3)判断是否有触发器-trigger存在其中,因为有可能说上次的触发器 并没有删除
//获得触发器 TriggerKey triggerKey = TriggerKey.triggerKey(config.getName(), config.getGroup()); CronTrigger trigger = (CronTrigger)scheduler.getTrigger(triggerKey);
4)创建一个任务类需要继承Job,实现方法execute。需要在其中执行定时任务如下:
//注释作用,当上一个任务未结束时下一个任务需进行等待
@DisallowConcurrentExecution
public class QuartzJobFactory implements Job {
public static final String SCHEDULEJOBKEY="scheduleJob";
//execute会根据cron的规则进行执行
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
Config config = (Config) jobExecutionContext.getMergedJobDataMap().get(SCHEDULEJOBKEY);
TaskUtils.invokMethod(config);
}
}5)将执行实例添加到任务当中去,我在例子是将执行任务的信息封装到了对象config当中然后在任务QuartzJobFactoryz中进行解读的
public static void invokMethod(Config config){
Object obj=null;
Class clazz=null;
//通过Spring上下文去找 也有可能找不到
try {
obj= SpringUtils.getBean(config.getClassPath().split("\\.")[config.getClassPath().split("\\.").length - 1]);
if (obj == null){
clazz = Class.forName(config.getClassPath());
obj = clazz.newInstance();
}else{
clazz =obj.getClass();
}
}catch (Exception e){
throw new RuntimeException("ERROR:TaskUtils is Bean Create please check the classpath is`t right or not");
}
Method method=null;
//获得方法名
try {
method = clazz.getDeclaredMethod(config.getMethodName());
} catch (NoSuchMethodException e) {
throw new RuntimeException("ERROR:TaskUtils is Bean the method Create please check the methodName is`t right or not");
}
//方法执行
try {
method.invoke(obj);
} catch (Exception e) {
throw new RuntimeException("ERROR:TaskUtils is Bean the method execute please check the methodName is`t right or not");
}
}
6)创建触发器并且绑定cron表达式
7)在调度器中将触发器和任务进行组合 详情见:com.study.www.service.QuartzTableservice.addJob
//将cron表达式进行转换 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(config.getCron()); //创建触发器并将cron表达式对象给塞入 trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withSchedule(cronScheduleBuilder).build(); //在调度器中将触发器和任务进行组合 scheduler.scheduleJob(jobDetail,trigger);
github:点击打开链接
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
标题名称:springbootQuartz动态修改cron表达式的方法
网页地址:http://www.jxjierui.cn/article/jgphjs.html


咨询
建站咨询
