//1.创建触发器 CronTrigger cronTrigger1 = TriggerBuilder.newTrigger() .withIdentity(jobName,jobGroup) .withSchedule(CronScheduleBuilder.cronSchedule(cron)) .build(); //2.创建jobDetail //反射获取类对象的三种方式:类.class、 Class.forName(类路径)、对象.getClass() JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(jobName)) .withIdentity(jobName, jobGroup) .build(); //3.将触发器和jobDetail加入到调度器中 scheduler.scheduleJob(jobDetail,cronTrigger1); //启动 配置类
/** * @Author: LJX * @DateTime: 2022/3/6 22:12 * @Description: 解决job注入到上下文中 */ @Configuration public class MyJobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory autowireCapableBeanFactory; @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object jobInstance = super.createJobInstance(bundle); //将job注入到上下文中 autowireCapableBeanFactory.autowireBean(jobInstance); return jobInstance; } }
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; /** * @Author: LJX * @DateTime: 2022/3/6 22:17 * @Description: 调度器配置,将调度器放入到spring上下文中 */ @Configuration public class QuartzConfig { @Autowired private MyJobFactory myJobFactory; @Bean //获取调度器 public Scheduler scheduler(){ //调度器来自于工厂对象中 //这个对象读取了配置文件和job也加入了spring上下文中 return schedulerFactoryBean().getScheduler(); } @Bean public SchedulerFactoryBean schedulerFactoryBean(){ //1.创建SchedulerFactoryBean对象 SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean(); //2.将配置文件内信息放入对象中 schedulerFactoryBean.setQuartzProperties(quartzProperties()); //3.将MyjobFactory放入到工厂对象中 schedulerFactoryBean.setJobFactory(myJobFactory); return schedulerFactoryBean; } /** * 创建读取自定义配置文件Properties类 * @return */ public Properties quartzProperties(){ try { //创建读取自定义配置文件Properties类 PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties")); propertiesFactoryBean.afterPropertiesSet(); return propertiesFactoryBean.getObject(); } catch (IOException e) { throw new RuntimeException(e); } } }