1.首先自定义一个Scheduler,任务调度器。记得@EnableScheduling
需要添加到启动类
2.采用spring自带@Scheduled
,定时去数据库扫码获取到任务,将任务添加到Quartz
3.将需要操作的任务一一实现Job接口,数据插入到数据库中。
代码如下
package com.mjitech.quartz;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
@Configuration
public class QuartzConfigration {
@Autowired
private MaxboxQuartzJobFactory jobFactory;
//获取工厂bean
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
try {
schedulerFactoryBean.setQuartzProperties(quartzProperties());
schedulerFactoryBean.setJobFactory(jobFactory);
} catch (IOException e) {
e.printStackTrace();
}
return schedulerFactoryBean;
}
//指定quartz.properties
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/conf/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
}
//创建schedule
@Bean(name = "scheduler")
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
package com.mjitech.quartz;
import lombok.Data;
import javax.persistence.*;
@Entity
@Table(name = "c_schedule_triggers")
@Data
public class CScheduleTrigger {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String cron; //时间表达式
private Boolean status; //使用状态 false:禁用 true:启用
private String jobName; //任务名称
private String jobGroup; //任务分组
}
package com.mjitech.quartz;
import com.mjitech.jpa.CScheduleTriggerRepository;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
@Component
public class ScheduleTriggerService {
private static final Logger logger = LoggerFactory.getLogger(ScheduleTriggerService.class);
@Autowired
private Scheduler scheduler;
@Autowired
private CScheduleTriggerRepository triggerRepository;
/**
*每分钟执行一次
* 将任务放进到数据库,自动读取放入队列
*/
@Scheduled(cron = "0 18 11 * * ?")
public void refreshTrigger() {
try {
//查询出数据库中所有的定时任务
List<CScheduleTrigger> jobList = triggerRepository.findAll();
if (!CollectionUtils.isEmpty(jobList)) {
for (CScheduleTrigger scheduleJob : jobList) {
Boolean status = scheduleJob.getStatus(); //该任务触发器目前的状态
TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
//说明本条任务还没有添加到quartz中
if (null == trigger) {
if (!status) { //如果是禁用,则不用创建触发器
continue;
}
JobDetail jobDetail = null;
try {
//创建JobDetail(数据库中job_name存的任务全路径,这里就可以动态的把任务注入到JobDetail中)
jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(scheduleJob.getJobName())).withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).build();
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron());
///设置定时任务的时间触发规则
trigger = TriggerBuilder.newTrigger().withIdentity(scheduleJob.getJobName(), scheduleJob.getJobGroup()).withSchedule(scheduleBuilder).build();
//把trigger和jobDetail注入到调度器
scheduler.scheduleJob(jobDetail, trigger);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} else {
//说明查出来的这条任务,已经设置到quartz中了
// Trigger已存在,先判断是否需要删除,如果不需要,再判定是否时间有变化
if (status.equals("0")) { //如果是禁用,从quartz中删除这条任务
JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
scheduler.deleteJob(jobKey);
continue;
}
String searchCron = scheduleJob.getCron(); //获取数据库的
String currentCron = trigger.getCronExpression();
if (!searchCron.equals(currentCron)) { //说明该任务有变化,需要更新quartz中的对应的记录
//表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(searchCron);
//按新的cronExpression表达式重新构建trigger
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
//按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, trigger);
}
}
}
}
} catch (Exception e) {
logger.error("定时任务每日刷新触发器任务异常,异常信息:", e);
}
}
}
package com.mjitech.quartz;
import com.mjitech.jpa.CScheduleTriggerRepository;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@DisallowConcurrentExecution
public class MyTask implements Job {
@Autowired
private CScheduleTriggerRepository jobRepository;
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
//可以通过context拿到执行当前任务的quartz中的很多信息,如当前是哪个trigger在执行该任务
CronTrigger trigger = (CronTrigger) jobExecutionContext.getTrigger();
String corn = trigger.getCronExpression();
String jobName = trigger.getKey().getName();
String jobGroup = trigger.getKey().getGroup();
System.out.println("开始了");
} catch (Exception e) {
}
}
}
package com.mjitech.quartz;
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
public class MaxboxQuartzJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}