摘要: 在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. CPU,寄存器,一缓二缓.... RAM ROM 外部存储器等简介

    自我学习:一.线程安全日期格式化操作的几种方式:1.每次new一个新对象:public static Date parse(String date) throws ParseException { r ...

  2. spring-boot + mybatis +pagehelper 使用分页

    转自:https://segmentfault.com/a/1190000015668715?utm_medium=referral&utm_source=tuicool 最近自己搭建一个sp ...

  3. 机器学习入门-Knn算法

    knn算法不需要进行训练, 耗时,适用于多标签分类情况 1. 将输入的单个测试数据与每一个训练数据依据特征做一个欧式距离. 2. 将求得的欧式距离进行降序排序,取前n_个 3. 计算这前n_个的y值的 ...

  4. display_css

    display所有可选值: none block inline inline-block inherit initial unset compact & marker list-item ru ...

  5. mysql trigger 设置错误ERROR1419

    mysql 触发器设置 background: mysql触发器可以在对数据库数据进行变更(插入,修改,删除)之前或之后触发操作. 在设置mysql触发器时提示: ERROR 1419 (HY000) ...

  6. git创建仓库,并提交代码(第一次创建并提交)(转)

    一直想学GIT,一直不曾学会.主要是GUI界面的很少,命令行大多记不住.今天尝试提交代码,按GIT上给的方法,没料到既然提交成功了. 于是把它记下来,方便以后学习. 代码是学习用的,没多大意义: 下图 ...

  7. LPSN获取菌python脚本

    本文转载于https://mp.weixin.qq.com/s?__biz=MzIxNzEzODA5NQ==&mid=2649373408&idx=1&sn=232c2cb36 ...

  8. 大型运输行业实战_day07_1_订单查看实现

    1.业务分析 每个在窗口售票的售票员都应该可以随时查看自己的售票信息 简单的界面入口如图所示: 对应的html代码: <button onclick="orderDetail()&qu ...

  9. MyBatis 通用Mapper接口 Example的实例

    一.mapper接口中的方法解析 mapper接口中的函数及方法 方法 功能说明 int countByExample(UserExample example) thorws SQLException ...

  10. java 里定义的方法参数 (final String... args)

    定义成final是为了防止在方法类里面修改参数,final String... args 为JDK新的特性,为可变长参数.编译的时候被解释为:public DCMException(final Str ...