摘要: 在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. sqlserver查询---分配cpu等资源

    数据库资源按需分配 https://www.cnblogs.com/i6first/p/4138365.html https://blog.csdn.net/kk185800961/article/d ...

  2. hive xml udf

    <store>   <book id="book"><title id="titile">hive</title> ...

  3. HTML5 Canvas ( 线性渐变, 升级版的星空 ) fillStyle, createLinearGradient, addColorStop

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  4. Gson 解析教程

    Gson 是google解析Json的一个开源框架,同类的框架fastJson,JackJson等等 本人fastJson用了两年,也是从去年才开始接触Gson,希望下面的总结会对博友有用,至于Gso ...

  5. VBA 公式中使用相对位置

    .Cells(3, 4).FormulaR1C1 = "=sum(r[-" & a & "]c[0]:r[-3]c[" & b & ...

  6. configparser 文件的生成和读写

    # configparser 生成 import configparser config = configparser.ConfigParser() config[DEFUALT] = {'Serve ...

  7. visual studio 2017 报错 无法下载安装文件。请检查Internet连接,然后重试

    vs下载完离线安装包在无网络环境下点击安装时出现无法下载安装文件.请检查Internet连接,然后重试 原因是证书没有导 解决方法 打开刚刚存放离线文件的路径,比如D:\vs2017offline,然 ...

  8. Python递归的经典案例

    目录 : 一.递归的简介 二.递归的经典应用   2.1 递归求阶乘   2.2 递归推斐波那契数列   2.3 二分法找有序列表指定值   2.4 递归解汉诺塔 前言: 当我们碰到诸如需要求阶乘或斐 ...

  9. Python中文件编码的检测

    前言: 文件打开的原则是“ 以什么编码格式保存的,就以什么编码格式打开 ”,我们常见的文件一般是以“ utf-8 ”或“ GBK ”编码进行保存的,由于编辑器一般设置了默认的保存和打开方式,所以我们在 ...

  10. oracle Hash Join及三种连接方式

    在Oracle中,确定连接操作类型是执行计划生成的重要方面.各种连接操作类型代表着不同的连接操作算法,不同的连接操作类型也适应于不同的数据量和数据分布情况. 无论是Nest Loop Join(嵌套循 ...