SpringBoot整合Quartz
一、Quartz
Quartz是一个完全由java编写的开源作业调度框架。
job - 任务- 你要做什么事?
Trigger - 触发器- 你什么时候去做?
Scheduler - 任务调度- 你什么时候需要去做什么事?
maven中添加相关依赖:
1 <dependency>
2 <groupId>org.quartz-scheduler</groupId>
3 <artifactId>quartz</artifactId>
4 </dependency>
创建Job类
1 public class QuartzJob implements Job {
2 public void execute(JobExecutionContext arg) throws JobExecutionException {
3 System.out.println("执行定时任务");
4 }
5 }
测试quartz
1 public static void main(String[] args) thwors Exception {
2 JobDetail jobDetail = JobBuilder.newJob(QuartzJob.class).build();
3 Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?"));
4 Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
5 scheduler.setScheduleJob(job, trigger);
6 scheduler.start();
7 }
二、SpringBoot整合Quartz
添加maven依赖
1 <dependency>
2 <groupId>org.quartz-scheduler</groupId>
3 <artifactId>quartz</artifactId>
4 <exclusions>
5 <exclusion>
6 <groupId>org.slf4j</groupId>
7 <artifactId>slf4j-api</artifactId>
8 </exclusion>
9 </exclusions>
10 </dependency>
11 <dependency>
12 <groupId>org.springframework</groupId>
13 <artifactId>spring-context-support</artifactId>
14 </dependency>
15 <dependency>
16 <groupId>org.springframework</groupId>
17 <artifactId>spring-tx</artifactId>
18 </dependency>
启动类开启定时任务
1 @SpringBootApplication
2 @EnableScheduling
3 public class App {
4 public static void main(String[] args) {
5 SpringAppliction.run(App.class, args);
6 }
7 }
编写一个适配器任务工厂,将实例化的任务手动添加到SpringIOC容器中完成对象的注入。
1 @Component("myAdaptableJobFactory")
2 public class MyAdaptableJobFactory extends AdaptableJobFactory {
3 @Autowired
4 private AutowireCapableBeanFactory autowireCapableBeanFactory;
5 protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
6 Object object = super.createJobInstance(bundle);
7 this.autowireCapableBeanFactory.autowireBean(object);
8 return object;
9 }
10 }
编写QuartzConfig
1 @Configuration
2 public class QuartzConfig {
3 //创建Job对象
4 @Bean
5 public JobDetailFactoryBean jobDetailFactoryBean() {
6 JobDetailFactoryBean factory = new JobDetailFactoryBean();
7 factory.setJobClass(QuartzJob.class);
8 return factory;
9 }
10 //创建Trigger对象
11 @Bean
12 public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetialFactoryBean) {
13 CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
14 factory.setJobDetail(jobDetailFactoryBean.getObject);
15 factory.setCronExpression("0/2 * * * * ?");
16 return factory;
17 }
18 //创建Scheduler对象
19 @Bean
20 public SchedulerFactoryBean schedulerFactoryBean(CronTriggerJobFactory cronTriggerJobFactory, MyAdaptableFactory myAdaptableFactory) {
21 SchedulerFactoryBean factory = new SchedulerFactoryBean();
22 factory.setTriggers(cronTriggerFactoryBean.getObject());
23 factory.setJobFactory(myAdaptableFactory);
24 return factory;
25 }
26 }