摘要: 在Spring Boot中使用Quartz时,在JOB中一般需要引用Spring管理的Bean,通过定义Job Factory实现自动注入

Spring有自己的Schedule定时任务,在Spring boot中使用的时候,不能动态管理JOB,于是就使用Quartz来实现。

在Spring Boot中配置Quartz:

import java.io.IOException;
import java.util.Properties; 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.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean; @Configuration
@EnableScheduling
public class QuartzSchedule { @Autowired
private MyJobFactory myJobFactory; @Bean
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setOverwriteExistingJobs(true); // 延时启动
factory.setStartupDelay(); // 加载quartz数据源配置
factory.setQuartzProperties(quartzProperties()); // 自定义Job Factory,用于Spring注入
factory.setJobFactory(myJobFactory); return factory;
} /**
* 加载quartz数据源配置
*
* @return
* @throws IOException
*/
@Bean
public Properties quartzProperties() throws IOException {
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
propertiesFactoryBean.afterPropertiesSet();
return propertiesFactoryBean.getObject();
} }

为了在JOB中使用Spring管理的Bean,需要重新定义一个Job Factory:

@Component
public class MyJobFactory extends AdaptableJobFactory { @Autowired
private AutowireCapableBeanFactory capableBeanFactory; @Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
// 调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
// 进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}

然后在JOB中就可以使用Spring管理的Bean了

public class MyJob implements Job, Serializable {
private static final long serialVersionUID = 1L;
private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired
private SomeService someService; @Override
public void execute(JobExecutionContext context) throws JobExecutionException {
someService.doSomething();
}
}

下面代码是创建JOB:

JobDetail jobDetail = JobBuilder.newJob(((Job) Class.forName(job.getClazz()).newInstance()).getClass())
.withIdentity(job.getJobName(), job.getJobGroup()).build();
jobDetail.getJobDataMap().put("extdata", job.getExtData()); // 表达式调度构建器
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
.withMisfireHandlingInstructionDoNothing();
// 构建一个trigger
TriggerBuilder<CronTrigger> triggerBuilder = TriggerBuilder.newTrigger().withIdentity(triggerKey)
.withSchedule(scheduleBuilder);
if (job.getStartTime() != null) {
triggerBuilder.startAt(job.getStartTime());
}
if (job.getEndTime() != null) {
triggerBuilder.endAt(job.getEndTime());
}
CronTrigger trigger = triggerBuilder.build(); scheduler.scheduleJob(jobDetail, trigger);// 注入到管理类

https://my.oschina.net/hhaijun/blog/698498

Spring Boot集成Quartz注入Spring管理的类的更多相关文章

  1. Spring Boot集成Shrio实现权限管理

    Spring Boot集成Shrio实现权限管理   项目地址:https://gitee.com/dsxiecn/spring-boot-shiro.git   Apache Shiro是一个强大且 ...

  2. boot中 Quartz注入spring管理类失败

    在项目中用到了Quartz,想在里面实现业务操作发现sping类注入总是失败.后来网上查询了一下解决办法.下面把我成功解决问题的这个版本发出来,大家一起学习一下. 在quartz 会发现 job中无法 ...

  3. Spring Boot集成quartz实现定时任务并支持切换任务数据源

    org.quartz实现定时任务并自定义切换任务数据源 在工作中经常会需要使用到定时任务处理各种周期性的任务,org.quartz是处理此类定时任务的一个优秀框架.随着项目一点点推进,此时我们并不满足 ...

  4. spring boot 集成 quartz 定时任务

    spring boot: @EnableScheduling开启计划任务支持,@Scheduled计划任务声明 1.pom.xml 引入依赖 <dependency> <groupI ...

  5. spring boot 整合quartz ,job不能注入的问题

    在使用spring boot 整合quartz的时候,新建定时任务类,实现job接口,在使用@AutoWire或者@Resource时,运行时出现nullpointException的问题.显然是相关 ...

  6. 玩转Spring Boot 集成Dubbo

    玩转Spring Boot 集成Dubbo 使用Spring Boot 与Dubbo集成,这里我之前尝试了使用注解的方式,简单的使用注解注册服务其实是没有问题的,但是当你涉及到使用注解的时候在服务里面 ...

  7. spring boot集成mybatis(1)

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  8. spring boot集成mybatis(2) - 使用pagehelper实现分页

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  9. 【SpringBoot】Spring Boot 集成SwaggerAPI

    Spring Boot 集成SwaggerAPI 文章目录 Spring Boot 集成SwaggerAPI Swagger 添加依赖 配置类 config 控制类 controller 接口测试 页 ...

随机推荐

  1. 温故而知新复习下PHP面向对象

    面向对象在PHP中是以类的形势展示的 PHP中的类是单继承的,用关键字extends来实现继承父类, 关键字public protected private 第一个是公开的 谁都可以访问,第二个只能本 ...

  2. ASP.NET CMS: Administration Template

    ASP.NET CMS: Administration Template For many creating advanced ASP.NET website or application admin ...

  3. ccttp图片处理过程

    1.python输出404的图片 #!/usr/bin/python # coding: utf-8 import psycopg2 import sys from datetime import * ...

  4. Ubuntu技巧之清理系统中无用的软件包

    如果你频繁的在你的系统中安装/卸载,那么不时的清理一下你的系统是十分必要的. 在Ubuntu终端中执行如下命令: sudo apt-get autoremove 屏幕输出是这个样子的: Reading ...

  5. Tomcat数据库连接池配置

    Tomcat数据库连接池配置 1.            Server.xml的配置 (1)找到tomcat所在目录下的conf\server.xml文件 (2)在文件最后一个</host> ...

  6. 简单AOP

    代码如下 //使用说明 //1,新加接口与类 //2,新加类并实现ICallHandler类: ExecuteHandler //3,新建特性并实现HandlerAttribute和重写其中的Crea ...

  7. mysql中binlog_format的三种模式

    mysql复制主要有三种方式:基于SQL语句的复制(statement-based replication, SBR),基于行的复制(row-based replication, RBR),混合模式复 ...

  8. prototype & __proto__

    [普通对象 vs 函数对象] js中对象分为两类,普通对象.函数对象.当在终端打印时,普通对象与函数对象有极其明显的差异. 一个不含杂七杂八的函数对象如下,这是第一种表现形式.: 若往里面塞东西,则会 ...

  9. android显示和隐藏软键盘

    显示键盘: EditText editText.setFocusable(true); editText.setFocusableInTouchMode(true); editText.request ...

  10. 最短路径Dijkstra算法(邻接矩阵)

    Dijkstra算法的原理: 从某个源点到其余各顶点的最短路径,即单源点最短路径(仅适合非负权值图).单源点最短路径是指:给定带权有向图G和源点v,求从v到G中其余各顶点的最短路径.迪杰斯特拉(Dij ...