这篇文章主要为大家展示了“SpringBoot如何实现quartz定时任务可视化管理功能”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“SpringBoot如何实现quartz定时任务可视化管理功能”这篇文章吧。
前言
在实际框架或产品开发过程中,springboot中集成quarzt方式基本是以job和trigger的bean对象方式直接硬编码完成的,例如以下代码示例。对于系统内定义的所有定时任务类型,具体执行类,执行策略,运行状态都没有一个动态全局的管理,所有决定将quartz做成可视化配置管理,便于统一管理,也降低了使用门槛,只需要关心job类的实现即可
@Bean public JobDetail SMSJobDetail) { return JobBuilder.newJobSMSJob.class).withIdentity"SMSJob").storeDurably).build); } // 把jobDetail注册到trigger上去 @Bean public Trigger myJobTrigger) { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule) .withIntervalInSeconds1).repeatForever); return TriggerBuilder.newTrigger) .forJobSMSJobDetail)) .withIdentity"myJobTrigger") .withSchedulescheduleBuilder) .build); }
表结构
用于存储quartz配置
DROP TABLE IF EXISTS `f_quartztask`; CREATE TABLE `f_quartztask` `TaskID` varchar50) NOT NULL, `TaskName` varchar200) DEFAULT NULL, `TaskType` int11) DEFAULT NULL, `TaskTag` varchar100) DEFAULT NULL, `JobClassPath` varchar200) DEFAULT NULL, `ExecutePeroid` int11) DEFAULT NULL, `ExecuteUnit` int11) DEFAULT NULL, `CornExpress` varchar200) DEFAULT NULL, `Enviroment` varchar50) DEFAULT NULL, `TaskStatus` int11) DEFAULT NULL, `SortNum` int11) DEFAULT NULL, `Remark` varchar500) DEFAULT NULL, PRIMARY KEY `TaskID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
枚举类
public class QuartzEnum { public enum TaskType implements IConvertEnumToCodeItem { Cycle10, "循环任务"), Corn20, "Corn表达式任务"); private int _value; private String _name; private TaskTypeint value, String name) { set_valuevalue); set_namename)); } public int get_value) { return _value; } public void set_valueint _value) { this._value = _value; } public String get_name) { return _name; } public void set_nameString _name) { this._name = _name; } @Override public String toString) { return _name; } @Override public String getCodeName) { return "Quartz任务类别"; } } public enum ExecuteUnit implements IConvertEnumToCodeItem { Second10, "秒"), Minute20, "分"), Hour30, "时"); private int _value; private String _name; private ExecuteUnitint value, String name) { set_valuevalue); set_namename)); } public int get_value) { return _value; } public void set_valueint _value) { this._value = _value; } public String get_name) { return _name; } public void set_nameString _name) { this._name = _name; } @Override public String toString) { return _name; } @Override public String getCodeName) { return "Quartz间隔单位"; } } public enum TaskStatus implements IConvertEnumToCodeItem { Open10, "开启"), Close20, "关闭"); private int _value; private String _name; private TaskStatusint value, String name) { set_valuevalue); set_namename)); } public int get_value) { return _value; } public void set_valueint _value) { this._value = _value; } public String get_name) { return _name; } public void set_nameString _name) { this._name = _name; } @Override public String toString) { return _name; } @Override public String getCodeName) { return "Quartz任务状态"; } } public enum TaskEnviroment implements IConvertEnumToCodeItem { All"全部", "全部"), Dev"dev", "开发环境"), Pro"pro", "正式环境"); private String _value; private String _name; private TaskEnviromentString value, String name) { set_valuevalue); set_namename)); } public String get_value) { return _value; } public void set_valueString _value) { this._value = _value; } public String get_name) { return _name; } public void set_nameString _name) { this._name = _name; } @Override public String toString) { return _name; } @Override public String getCodeName) { return "Quartz任务执行环境"; } } }
QuartzFactory
支持Job类注bean入对象
@Component public class QuartzFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory capableBeanFactory; @Override protected Object createJobInstanceTriggerFiredBundle bundle) throws Exception { // 调用父类的方法 Object jobInstance = super.createJobInstancebundle); // 进行注入 capableBeanFactory.autowireBeanjobInstance); return jobInstance; } }
QuartzConfig
注入QuartzFactory对象
@Configuration public class QuartzConfig { @Autowired private QuartzFactory quartzFactory; @Bean public SchedulerFactoryBean schedulerFactoryBean){ SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean); schedulerFactoryBean.setJobFactoryquartzFactory); //将job实例化,能够操作进行Spring 注入 return schedulerFactoryBean; } }
QuartzUtil
定时任务动态添加/删除操作类,initQuartzTask方法在系统启动时执行,根据配置自动开启相关符合条件的任务
@Component public class QuartzUtil { @Autowired private SchedulerFactoryBean schedulerFactoryBean; @Autowired private F_QuartzTaskService quartzTaskService; @Value"${spring.profiles.active}") private String active; private static String JOB_GROUP_NAME = "DEFAULT_JOB_GROUP_NAME"; private static String TRIGGER_GROUP_NAME = "DEFAULT_TRIGGER_GROUP_NAME"; public void initQuartzTask) { List<F_QuartzTaskDO> openTaskList = quartzTaskService.selectAllList); ifopenTaskList.size)>0){ openTaskList = openTaskList.stream).filtera -> a.getTaskStatus) == QuartzEnum.TaskStatus.Open.get_value) && a.getEnviroment).equalsQuartzEnum.TaskEnviroment.All.get_name)) || a.getEnviroment).equalsactive))).collectCollectors.toList)); } for F_QuartzTaskDO taskDO : openTaskList) { try { Class<Job> jobClass = Class<Job>) Class.forNametaskDO.getJobClassPath)); if taskDO.getTaskType) == QuartzEnum.TaskType.Cycle.get_value)) { addIntervalJobtaskDO.getTaskTag), jobClass, taskDO.getExecutePeroid), taskDO.getExecuteUnit)); } else { addCornJobtaskDO.getTaskTag), jobClass, taskDO.getCornExpress)); } } catch Exception e) { e.printStackTrace); } } if openTaskList.size) > 0) { System.out.println"扫描并初始化开启quartz定时任务成功,任务数量:" + openTaskList.size) + "个"); } } public void startTask F_QuartzTaskDO taskDO){ try { Class<Job> jobClass = Class<Job>) Class.forNametaskDO.getJobClassPath)); if taskDO.getTaskType) == QuartzEnum.TaskType.Cycle.get_value)) { addIntervalJobtaskDO.getTaskTag), jobClass, taskDO.getExecutePeroid), taskDO.getExecuteUnit)); } else { addCornJobtaskDO.getTaskTag), jobClass, taskDO.getCornExpress)); } } catch Exception e) { e.printStackTrace); } } //增加定时任务任务 public void addIntervalJobString jobName, Class<? extends Job> cls, int peroid, int timeUnit) { try { SimpleScheduleBuilder scheduleBuilder = null; if timeUnit == QuartzEnum.ExecuteUnit.Second.get_value)) { scheduleBuilder = SimpleScheduleBuilder.simpleSchedule).withIntervalInSecondsperoid).repeatForever); } else if timeUnit == QuartzEnum.ExecuteUnit.Minute.get_value)) { scheduleBuilder = SimpleScheduleBuilder.simpleSchedule).withIntervalInMinutesperoid).repeatForever); } else if timeUnit == QuartzEnum.ExecuteUnit.Hour.get_value)) { scheduleBuilder = SimpleScheduleBuilder.simpleSchedule).withIntervalInHoursperoid).repeatForever); } Scheduler sched = schedulerFactoryBean.getScheduler); JobDetail jobDetail = JobBuilder.newJobcls).withIdentityjobName, JOB_GROUP_NAME).storeDurably).build); Trigger trigger = TriggerBuilder.newTrigger).forJobjobDetail).withIdentityjobName, TRIGGER_GROUP_NAME).withSchedulescheduleBuilder).build); sched.scheduleJobjobDetail, trigger); if !sched.isShutdown)) { sched.start); // 启动 } } catch Exception e) { throw new RuntimeExceptione); } } //增加corn表达式任务 public void addCornJobString jobName, Class<? extends Job> cls, String cornExpress) { try { Scheduler sched = schedulerFactoryBean.getScheduler); JobDetail jobDetail = JobBuilder.newJobcls).withIdentityjobName, JOB_GROUP_NAME).build); CronTrigger trigger = CronTrigger) TriggerBuilder .newTrigger) .withIdentityjobName, TRIGGER_GROUP_NAME) .withScheduleCronScheduleBuilder.cronSchedulecornExpress)) .build); sched.scheduleJobjobDetail, trigger); if !sched.isShutdown)) { sched.start); // 启动 } } catch Exception e) { throw new RuntimeExceptione); } } //停止任务 public void deleteJobString jobName) { try { Scheduler sched = schedulerFactoryBean.getScheduler); TriggerKey triggerKey = TriggerKey.triggerKeyjobName, TRIGGER_GROUP_NAME); JobKey jobKey = JobKey.jobKeyjobName, JOB_GROUP_NAME); sched.pauseTriggertriggerKey); // 停止触发器 sched.unscheduleJobtriggerKey);// 移除触发器 sched.deleteJobjobKey); // 删除任务 } catch Exception e) { throw new RuntimeExceptione); } } }
界面展示