quartz小伙伴们知道吗?今天我们就来了解一下springboot整合quartz,来看看它要如何配置吧。
一、添加maven依赖
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> </exclusions> </dependency> < dependency > <groupId>org.springframework</groupId> < artifactId > spring - context - support < /artifactId> < /dependency> < dependency > <groupId>org.springframework</groupId> < artifactId > spring - tx < /artifactId> < /dependency>
二、启动类开启定时任务
@SpringBootApplication @EnableScheduling public class App { public static void main(String[] args) { SpringAppliction.run(App.class, args); } }
三、编写一个适配器任务工厂,把已经实例化的任务手动添加到SpringIOC容器中完成对象注入
@Component("myAdaptableJobFactory") public class MyAdaptableJobFactory extends AdaptableJobFactory { @Autowired private AutowireCapableBeanFactory autowireCapableBeanFactory; protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { Object object = super.createJobInstance(bundle); this.autowireCapableBeanFactory.autowireBean(object); return object; } }
四、编写QuartzConfig配置文件
@Configuration public class QuartzConfig { //创建Job对象 @Bean public JobDetailFactoryBean jobDetailFactoryBean() { JobDetailFactoryBean factory = new JobDetailFactoryBean(); factory.setJobClass(QuartzJob.class); return factory; } //创建Trigger对象 @Bean public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetialFactoryBean) { CronTriggerFactoryBean factory = new CronTriggerFactoryBean(); factory.setJobDetail(jobDetailFactoryBean.getObject); factory.setCronExpression("0/2 * * * * ?"); return factory; } //创建Scheduler对象 @Bean public SchedulerFactoryBean schedulerFactoryBean(CronTriggerJobFactory cronTriggerJobFactory, MyAdaptableFactory myAdaptableFactory) { SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setTriggers(cronTriggerFactoryBean.getObject()); factory.setJobFactory(myAdaptableFactory); return factory; } }
这样我们就成功整合了quartz。
以上就是本篇文章的所有内容,如果小伙伴对一些java项目中常见问题还有疑问的话,可以来我们网站了解答案及详情。
推荐阅读: