Quartz的基本概念和配置已经在上一篇中具体说明了。
本次看看如何实现。
(1)数据模型---JobModel。
页面录入,最后会保存在数据库中。
public class JobModel extends BaseEntity<Long> {
private static final long serialVersionUID = -2458935535811207209L;
//job名
private String jobName;
//job描述
private String description;
//cron表达式
private String cron;
//springBeanName
private String springBeanName;
//方法名
private String methodName;
private int status;
}
(2)saveJob的实现
1、检查JobModel---确认是否含有无参方法,没有则抛出异常
2、创建Job
3、创建cronTrigger
4、修改或注册任务和定时器
5、数据库保存Job
public void saveJob(JobModel jobModel) {
checkJobModel(jobModel);
//1、创建job
String name = jobModel.getJobName();
JobKey jobKey = JobKey.jobKey(name);
JobDetail jobDetail = JobBuilder.newJob(SpringBeanJob.class).storeDurably()
.withDescription(jobModel.getDescription()).withIdentity(jobKey).build();
//将job_key存入JobDataMap
jobDetail.getJobDataMap().put(JOB_DATA_KEY, jobModel);
//创建cronSchedule
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(jobModel.getCron());
//2、创建cronTrigger
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(name).withSchedule(cronScheduleBuilder)
.forJob(jobKey).build();
try {
boolean exists = scheduler.checkExists(jobKey);
if (exists) {
//3、修改一个定时任务,主要是更改trigger:
scheduler.rescheduleJob(new TriggerKey(name), cronTrigger);
//scheduler可以看成是一个容器,对JobDetail进行增删改查
// false表示不替换,ture表示替换,既更新;另外一般使用 比较方便sched.scheduleJob(job, trigger);
scheduler.addJob(jobDetail, true);
} else {
//3、注册任务和定时器
scheduler.scheduleJob(jobDetail, cronTrigger);
}
//4、保存Job
JobModel model = jobDao.getByName(name);
if (model == null) {
jobDao.save(jobModel);
} else {
jobDao.update(jobModel);
}
} catch (SchedulerException e) {
log.error("新增或修改job异常", e);
}
}
(3)doJob的实现
执行jobModel中bean的method。
public void doJob(JobDataMap jobDataMap) {
JobModel jobModel = (JobModel) jobDataMap.get(JOB_DATA_KEY);
String beanName = jobModel.getSpringBeanName();
String methodName = jobModel.getMethodName();
Object object = applicationContext.getBean(beanName);
try {
log.info("job:bean:{},方法名:{}", beanName, methodName);
Method method = object.getClass().getDeclaredMethod(methodName);
method.invoke(object);
} catch (Exception e) {
e.printStackTrace();
}
}
(4)deleteJob的实现
public void deleteJob(Long id) throws SchedulerException {
JobModel jobModel = jobDao.getById(id);
if (jobModel.getIsSysJob() != null && jobModel.getIsSysJob()) {
throw new IllegalArgumentException("该job是系统任务,不能删除,因为此job是在代码里初始化的,删除该类job请先确保相关代码已经去除");
}
String jobName = jobModel.getJobName();
JobKey jobKey = JobKey.jobKey(jobName);
scheduler.pauseJob(jobKey);
scheduler.unscheduleJob(new TriggerKey(jobName));
scheduler.deleteJob(jobKey);
jobModel.setStatus(0);
jobDao.update(jobModel);
}
(5)启动思路
JOB和Trigger操作
1、执行---SpringBeanJob.executeInternal---jobService.doJob
2、修改和保存---jobService.saveJob---scheduler.addJob+存库中+状态1
3、删除---jobService.deleteJob---scheduler.pauseJob+unscheduleJob+deleteJob+删除库+状态0
Scheduler操作(调度器)----JobConfig.quartzScheduler---启动调度器
|