背景

最近在做项目,项目中有个需求:需要使用定时任务,这个定时任务需要即时生效。
查看Quartz官网之后发现:Quartz提供两种基本作业存储类型:

  • RAMJobStore :RAM也就是内存,默认情况下Quartz会将任务调度存在内存中,这种方式性能是最好的,因为内存的速度是最快的。不好的地方就是数据缺乏持久性,但程序崩溃或者重新发布的时候,所有运行信息都会丢失
  • JDBC作业存储:存到数据库之后,可以做单点也可以做集群,当任务多了之后,可以统一进行管理。关闭或者重启服务器,运行的信息都不会丢失。缺点就是运行速度快慢取决于连接数据库的快慢。

SpringBoot集成Quartz

我们也可以自己去将quartz和springBoot整合在一起,其实说是springBoot还不如说是sping,因为我们没有用到spirngboot的相关的快捷方式。
如果童鞋们想快速集成Quartz,立刻看到效果的话,可以直接往下翻,直接看SpirngBoot自带的Quartz插件。但我建议大家还是从spring整合Quartz开始,懂的原理,方有收获。

Quartz初始化表

如果需要做持久化的话,数据肯定是要存在数据库的,那么到底存在哪些表呢?其实官网文档也跟我们讲过了,地址如下:
http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-09.html
其中有句话:

JDBCJobStore works with nearly any database, it has been used widely with Oracle, PostgreSQL, MySQL, MS SQLServer, HSQLDB, and DB2. To use JDBCJobStore, you must first create a set of database tables for Quartz to use. You can find table-creation SQL scripts in the “docs/dbTables” directory of the Quartz distribution.
大概就是支持这么多的数据库类型。如果你要使用JDBCJoBStore的话,你先要创建一些表,这些表在 “doc/dbTables”里面。“doc/dbTables” 在哪儿呢?其实都在源码里面,直接到官网下下来就行了。

Spring整合Quartz

pom文件

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz-jobs</artifactId>
<!-- <version>2.3.0</version> -->
</dependency>
<!--定时任务需要依赖context模块-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--&lt;!&ndash; druid数据库连接池 &ndash;&gt;-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>

对应的properties 文件

#使用自己的配置文件
org.quartz.jobStore.useProperties:true #默认或是自己改名字都行
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
#如果使用集群,instanceId必须唯一,设置成AUTO
org.quartz.scheduler.instanceId = AUTO org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true #存储方式使用JobStoreTX,也就是数据库
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
#是否使用集群(如果项目只部署到 一台服务器,就不用了)
org.quartz.jobStore.isClustered = false
org.quartz.jobStore.clusterCheckinInterval=20000
org.quartz.jobStore.tablePrefix = qrtz_
org.quartz.jobStore.dataSource = myDS #配置数据源
#数据库中quartz表的表名前缀
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/aipyun?serverTimezone=GMT&characterEncoding=utf-8
org.quartz.dataSource.myDS.user = root
org.quartz.dataSource.myDS.password = root123
org.quartz.dataSource.myDS.maxConnections = 5

核心QuartzConfiguration类:

ackage com.cj.config;

import org.quartz.Scheduler;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean; /**
* 描述 : quartz 配置信息
*
* @author caojing
* @create 2018-12-24-16:47
*/
@Configuration
public class QuartzConfiguration {
@Autowired
private JobFactory jobFactory; @Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(jobFactory);
// 用于quartz集群,QuartzScheduler 启动时更新己存在的Job
schedulerFactoryBean.setOverwriteExistingJobs(true);
//延长启动
schedulerFactoryBean.setStartupDelay(1);
//设置加载的配置文件
schedulerFactoryBean.setConfigLocation(new ClassPathResource("/quartz.properties"));
return schedulerFactoryBean;
} @Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}

这其中我们把2个类的初始化移到了IOC中,因为之前Quartz的实例化是自己去控制的,为什么要这么做后面会有讲到。
一个是SchedulerFactoryBean类,这个类其实就是之前xml配置中的SchedulerFactoryBean。附上之前xml配置如下(这里不需要配置,springboot建议我们少用xml配置)

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="oceanStatusCronTrigger"/>
</list>
</property>
</bean>

这个类我相信只要用过xml配置的人一定很熟悉,这是Quartz入口。同时也是spring 和Scheduler 关系的桥梁。以便在Spring容器启动后,Scheduler自动开始工作,而在Spring容器关闭前,自动关闭Scheduler。

JobFactory类

package com.cj.config;

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import org.springframework.stereotype.Component; /**
* 描述:
*
* @author caojing
* @create 2018-12-26-14:03
*/
@Component
public class JobFactory extends AdaptableJobFactory { @Autowired
private AutowireCapableBeanFactory capableBeanFactory; @Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
// 调用父类的方法
Object jobInstance = super.createJobInstance(bundle);
// 进行注入
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}

这个类的作用就是讲Job的实例化交给IOC去进行。
其实问题在于:

Job对象的实例化过程是在Quartz中进行的,注入的实体类是在Spring容器当中的 所以在job中无法注入Srping容器的实体类。

如何纳入:Job的创建都是通过JobFactory创建的。JobFactory 有2个实现类:AdaptableJobFactory 和 SimpleJobFactory:

  • 自定义的工厂类 JobFactory 继承 AdaptableJobFactory 。
  • 通过调用父类 AdaptableJobFactory 的方法createJobInstance来实现对Job的实例化。
  • 在Job实例化完以后,再调用自身方法为创建好的Job实例进行属性自动装配并将其纳入到Spring容器的管理之中。(通过AutowireCapableBeanFactory纳入)。

UploadTask 类:

package com.cj.quartzdemo;
import com.cj.controller.IndexController;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service; import java.util.Date; /**
* 描述:
*
* @author caojing
* @create 2018-12-25-11:38
*/
@Component
@DisallowConcurrentExecution
public class UploadTask extends QuartzJobBean {
@Autowired
private IndexController indexController;
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println(new Date() + "任务开始------------------------------------");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new Date() + "任务结束------------------------------------");
}
}

继承QuartzJobBean类,重写executeInternal方法。
附:DisallowConcurrentExecution 比如job执行10秒,任务是每隔5秒执行,加上这个注解,程序就会等10秒结束后再执行下一个任务。

indexController类:

package com.cj.controller;

import com.cj.quartzdemo.UploadTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; /**
* 描述:
*
* @author caojing
* @create 2018-12-26-14:11
*/
@Controller
public class IndexController {
@Autowired
private Scheduler scheduler; @RequestMapping(value = "/index", method = RequestMethod.GET)
public void index() throws SchedulerException {
//cron表达式
CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/8 * * * * ?");
//根据name 和group获取当前trgger 的身份
TriggerKey triggerKey = TriggerKey.triggerKey("cj", "123");
CronTrigger triggerOld = null;
try {
//获取 触发器的信息
triggerOld = (CronTrigger) scheduler.getTrigger(triggerKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
if (triggerOld == null) {
//将job加入到jobDetail中
JobDetail jobDetail = JobBuilder.newJob(UploadTask.class).withIdentity("cj", "123").build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("cj","123").withSchedule(cronScheduleBuilder).build();
//执行任务
scheduler.scheduleJob(jobDetail, trigger);
} else {
System.out.println("当前job已存在--------------------------------------------");
}
}
}

浏览器输入 http://localhost:8080/index 就可以看到数据库已经存储了我们写的cron表达式和相应的类。
查看数据库表(qrtz_cron_triggers)附上截图:

至此,job 已经被我们成功持久化到数据库。我们来回顾下整体的一个流程。

pom文件添加对应的依赖。
mysql数据库对应表的初始化。
配置对应的properties
将原来quartz控制的类的实例化交给spirng IOC控制。(对应的是核心QuartzConfiguration类和JobFactory类)
业务逻辑层对job进行控制。

SpringBoot整合Quartz定时任务(持久化到数据库)的更多相关文章

  1. springboot整合quartz并持久化到数据库

    首先,这里的持久化是是如果当服务器宕机时,任务还在为我们保存.并且在启动服务器之后仍然可以自动执行 一.创建quartz 建表语句mysql的,quartz 2.3.0版本 DROP TABLE IF ...

  2. SpringBoot整合Quartz定时任务 系统job Spring Boot教程 调度任务

    原文地址:https://www.cnblogs.com/allalongx/p/8477368.html 构建工程 创建一个Springboot工程,在它的程序入口加上@EnableScheduli ...

  3. SpringBoot整合Quartz定时任务

    记录一个SpringBoot 整合 Quartz 的Demo实例 POM.XML文件 <!-- 定时器任务 quartz需要导入的坐标 --> <dependency> < ...

  4. SpringBoot整合Quartz定时任务 的简单实例 2

    (1)什么是Quartz?(2)Quartz的特点:(3)Quartz专用词汇说明:(4)Quartz任务调度基本实现原理: 接下来看下具体的内容: (1)什么是Quartz? Quartz是一个完全 ...

  5. SpringBoot整合Quartz定时任务 的简单实例

    POM.XML文件 <!-- 定时器任务 quartz需要导入的坐标 --> <dependency> <groupId>org.quartz-scheduler& ...

  6. SpringBoot整合quartz实现动态启动,停止定时任务功能

    注意:这个方法当程序重启之后会失效,所以必须将定时任务持久化到数据库,然后程序启动的时候重新把数据库的定时任务加载到quartz中 springboot程序启动初始化代码参考:https://www. ...

  7. Spring整合Quartz定时任务 在集群、分布式系统中的应用(Mysql数据库环境)

    Spring整合Quartz定时任务 在集群.分布式系统中的应用(Mysql数据库环境)   转载:http://www.cnblogs.com/jiafuwei/p/6145280.html 单个Q ...

  8. Spring整合Quartz定时任务执行2次,Spring定时任务执行2次

    Spring整合Quartz定时任务执行2次,Spring定时任务执行2次 >>>>>>>>>>>>>>>&g ...

  9. SpringBoot整合Quartz及log4j实例

    SpringBoot整合Quartz及log4j实例 因为之前项目中经常会做一些定时Job的东西,所以在此记录一下,目前项目中已经使用elastic-job,这个能相对比Quartz更加简单方便一些, ...

随机推荐

  1. python得到当前版本号

    import sys print(sys.winver) 3.7 # 导入sys模块的argv,winver成员,并为其指定别名v.wv from sys import argv as v, winv ...

  2. Spark的安装和使用

    根据Spark2.1.0入门:Spark的安装和使用在虚拟机安装Spark,并进行测试 实验3  Spark读取文件系统的数据 将文件上传hdfs (1)在spark-shell中读取Linux系统本 ...

  3. [刘阳Java]_Web前端入门级练习_迅雷首页第一屏设计

    今天接着上一篇文章<Web前端入门级练习_迅雷官宣网设计>正式开始迅雷首页第一版的设计.如果完成,则最终的效果图如下 第一步:先完成logo部分的设计 logo设计,我们会使用CSS的定位 ...

  4. Requests方法 -- Blog流程类进行关联

    1.接口封装关联 1.有些接口经常会用到比如登录的接口,这时候我们可以每个接口都封装成一个方法,如:登录.保存草稿.发帖.删帖,这四个接口就可以写成四个方法2.接口封装好了后,后面我们写用例那就直接调 ...

  5. 解决 centerOS7部署ajango2.2.x版本 报SQLite 3.8.3 or later is required (found 3.7.17).错误

    在CentOS7上部署Django的时候,遇到了一些问题,写篇笔记记录解决过程. 报错信息 当python3 manage.py runserver启动django项目的时候,就会出现报错信息如下: ...

  6. 单点登录详解(token简述)(七)

    前言 为什么整理单点登录? 主要的原因还是自己以前学习的时候曾经用过,但是时间太久,忘记了里面用到了哪些技术.及如何实现的,每次想到单点登录总是感觉即会又不会,这次整理session时,又涉及到了单点 ...

  7. Spring Cloud Alibaba基础教程:Nacos+Dubbo

    Spring Cloud Alibaba为分布式应用程序开发提供了一站式解决方案. 它包含开发分布式应用程序所需的所有组件,使您可以轻松地使用Spring Cloud开发应用程序.Dubbo是Alib ...

  8. css--实现一个文字少时居中,文字换行时居左的样式

    前言 最近群里的小伙伴去面试,遇到这样一个问题,面试官问:"用 css 对一行文字进行布局,当文字不够换行的时候,这行文字要居中显示,当文字出现换行的时候,这行文字要靠左显示.", ...

  9. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax

    基本介绍 XmlHttpRequest XmlHttpRequest是JavaScript中原生的,历史悠久的一种发送网络请求的方案. 基本上所有前端框架对于网络请求的部分都是基于它来完成的. 在本章 ...

  10. 关于Servlet技术

    1.Servlet 技术           a)什么是 Servlet                     1.Servlet 是 JavaEE 规范之一.规范就是接口              ...