在Java应用程序中调度作业时,Quartz是第一个考虑的工具。
Quartz是由最流行的RDBMS支持的作业调度程序。 这真的很方便,并且很容易与spring集成。
为了创建石英模式,您必须下载石英发行版并解压缩位于crystal-2.2.3 / docs / dbTables /中的文件夹。

根据您使用的数据库选择石英模式。 在我们的例子中,我们将使用本地h2数据库,因此将使用tables_h2.sql模式。
为了避免任何手动的SQL操作,我将使用Spring Boot数据库初始化功能。

让我们从gradle文件开始。

group 'com.gkatzioura'
version '1.0-SNAPSHOT'apply plugin: 'java'sourceCompatibility = 1.8buildscript {repositories {mavenCentral()}dependencies {classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")}
}apply plugin: 'idea'
apply plugin: 'spring-boot'repositories {mavenCentral()
}dependencies {compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.3.3.RELEASE'compile group: 'org.springframework', name: 'spring-context-support', version: '4.2.4.RELEASE'compile group: 'org.springframework', name:'spring-jdbc', version: '4.2.4.RELEASE'compile group: 'org.quartz-scheduler', name: 'quartz', version: '2.2.3'compile group: 'ch.qos.logback', name: 'logback-core', version:'1.1.3'compile group: 'ch.qos.logback', name: 'logback-classic',version:'1.1.3'compile group: 'org.slf4j', name: 'slf4j-api',version:'1.7.13'compile group: 'com.h2database', name: 'h2', version:'1.4.192'testCompile group: 'junit', name: 'junit', version: '4.11'
}

除了石英,spring和h2依赖关系之外,我们还添加了spring-jdbc依赖关系,因为我们希望通过spring初始化数据库。

我们还将添加一个application.yml文件

spring:datasource:continueOnError: true
org:quartz:scheduler:instanceName: spring-boot-quartz-demoinstanceId: AUTOthreadPool:threadCount: 5
job:startDelay: 0repeatInterval: 60000description: Sample jobkey: StatisticsJob

由于架构创建语句(如果不存在则缺少创建),我将spring.datasource.continueOnError设置为false。 根据您的实施,解决方法将有所不同。

应用类别

package com.gkatzioura.springquartz;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;/*** Created by gkatzioura on 6/6/16.*/
@SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication springApplication = new SpringApplication();ApplicationContext ctx = springApplication.run(Application.class,args);}
}

H2数据源配置由石英支持

package com.gkatzioura.springquartz.config;import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;/*** Created by gkatzioura on 6/6/16.*/
@Configuration
public class QuartzDataSource {//Since it a test database it will be located at the temp directoryprivate static final String TMP_DIR = System.getProperty("java.io.tmpdir");@Beanpublic DataSource dataSource() {JdbcDataSource ds = new JdbcDataSource();ds.setURL("jdbc:h2:"+TMP_DIR+"/test");return ds;}}

在我们的情况下,我们希望每分钟发送一次“垃圾邮件”电子邮件,因此我们定义了一个简单的电子邮件服务

package com.gkatzioura.springquartz.service;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;/*** Created by gkatzioura on 6/7/16.*/
@Service
public class EmailService {private static final Logger LOGGER = LoggerFactory.getLogger(EmailService.class);public void sendSpam() {LOGGER.info("Should send emails");}}

我还将实现一个SpringBeanJobFactory

package com.gkatzioura.springquartz.quartz;import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;/*** Created by gkatzioura on 6/7/16.*/
public class QuartzJobFactory extends SpringBeanJobFactory implements ApplicationContextAware {private transient AutowireCapableBeanFactory beanFactory;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {beanFactory = applicationContext.getAutowireCapableBeanFactory();}@Overrideprotected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {final Object job = super.createJobInstance(bundle);beanFactory.autowireBean(job);return job;}
}

QuartzJobFactory将创建作业实例,并将使用应用程序上下文来注入定义的任何依赖项。

下一步是定义我们的工作

package com.gkatzioura.springquartz.job;import com.gkatzioura.springquartz.service.EmailService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;/*** Created by gkatzioura on 6/6/16.*/
public class EmailJob implements Job {@Autowiredprivate EmailService cronService;@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {cronService.sendSpam();}
}

最后一步是添加石英配置

package com.gkatzioura.springquartz.config;import com.gkatzioura.springquartz.job.EmailJob;
import com.gkatzioura.springquartz.quartz.QuartzJobFactory;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;import javax.sql.DataSource;
import java.util.Properties;/*** Created by gkatzioura on 6/7/16.*/
@Configuration
public class QuartzConfig {@Value("${org.quartz.scheduler.instanceName}")private String instanceName;@Value("${org.quartz.scheduler.instanceId}")private String instanceId;@Value("${org.quartz.threadPool.threadCount}")private String threadCount;@Value("${job.startDelay}")private Long startDelay;@Value("${job.repeatInterval}")private Long repeatInterval;@Value("${job.description}")private String description;@Value("${job.key}")private String key;@Autowiredprivate DataSource dataSource;@Beanpublic org.quartz.spi.JobFactory jobFactory(ApplicationContext applicationContext) {QuartzJobFactory sampleJobFactory = new QuartzJobFactory();sampleJobFactory.setApplicationContext(applicationContext);return sampleJobFactory;}@Beanpublic SchedulerFactoryBean schedulerFactoryBean(ApplicationContext applicationContext) {SchedulerFactoryBean factory = new SchedulerFactoryBean();factory.setOverwriteExistingJobs(true);factory.setJobFactory(jobFactory(applicationContext));Properties quartzProperties = new Properties();quartzProperties.setProperty("org.quartz.scheduler.instanceName",instanceName);quartzProperties.setProperty("org.quartz.scheduler.instanceId",instanceId);quartzProperties.setProperty("org.quartz.threadPool.threadCount",threadCount);factory.setDataSource(dataSource);factory.setQuartzProperties(quartzProperties);factory.setTriggers(emailJobTrigger().getObject());return factory;}@Bean(name = "emailJobTrigger")public SimpleTriggerFactoryBean emailJobTrigger() {SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();factoryBean.setJobDetail(emailJobDetails().getObject());factoryBean.setStartDelay(startDelay);factoryBean.setRepeatInterval(repeatInterval);factoryBean.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT);return factoryBean;}@Bean(name = "emailJobDetails")public JobDetailFactoryBean emailJobDetails() {JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();jobDetailFactoryBean.setJobClass(EmailJob.class);jobDetailFactoryBean.setDescription(description);jobDetailFactoryBean.setDurability(true);jobDetailFactoryBean.setName(key);return jobDetailFactoryBean;}
}

我们所做的是使用定义的QuartzJobFactory创建调度程序工厂bean,并注册了作业运行所需的触发器。 在我们的案例中,我们实现了一个简单的触发器,每分钟运行一次。

您可以在github上找到源代码

翻译自: https://www.javacodegeeks.com/2016/06/integrating-quartz-spring.html

将Quartz与Spring集成相关推荐

  1. Quartz学习总结(1)——Spring集成Quartz框架

    一.Quartz简介 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,它可以与J2EE与J2SE应用程序相结合也可以单独使用.Quartz可以用来创建简 ...

  2. spring集成quartz报org.springframework.scheduling.quartz.CronTriggerBean异常

    spring集成quartz项目做定时任务,但是启动tomcat报错: ClassNotFoundException: org.springframework.scheduling.quartz.Cr ...

  3. Quartz 在 Spring 中如何动态配置时间

    在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度. 有关调度的实现我就第一就想到了Quartz这个开源调度组件,因为很多项目使用过,Spring结合Quartz静态配置调度任务时间 ...

  4. Quartz 在 Spring 中如何动态配置时间--转

    原文地址:http://www.iteye.com/topic/399980 在项目中有一个需求,需要灵活配置调度任务时间,并能自由启动或停止调度.  有关调度的实现我就第一就想到了Quartz这个开 ...

  5. Spring集成Activemq使用

    现在任何一个框架的使用都会结合spring框架,quartz.cxf与平时常见的Hibernate.mybatis.Struts等都可以与spring集成起来使用,在这里研究了activemq结合sp ...

  6. Spring Cloud Task 主要是干什么的啊?跟 Quartz 和 Spring Task 有啥关系?

    背景 项目开发中涉及到分布式定时任务调度,且任务处理时又涉及到了数据分片. 最先想到的任务调度框架是 Quartz 和 Spring Task ,分析它们的特点后,发现存在两个问题: Quartz 的 ...

  7. 阿里RocketMq试用记录+简单的Spring集成

    CSDN学院招募微信小程序讲师啦      程序猿全指南,让[移动开发]更简单!        [观点]移动原生App开发 PK HTML 5开发     云端应用征文大赛,秀绝招,赢无人机! 阿里R ...

  8. java timer cron_Java之旅--定时任务(Timer、Quartz、Spring、LinuxCron)

    在Java中,实现定时任务有多种方式.本文介绍4种.Timer和TimerTask.Spring.QuartZ.Linux Cron. 以上4种实现定时任务的方式.Timer是最简单的.不须要不论什么 ...

  9. Spring集成Redis方案(spring-data-redis)(基于Jedis的单机模式)(待实践)

    说明:请注意Spring Data Redis的版本以及Spring的版本!最新版本的Spring Data Redis已经去除Jedis的依赖包,需要自行引入,这个是个坑点.并且会与一些低版本的Sp ...

最新文章

  1. C++——智能指针——auto_ptr、shared_ptr、unique_ptr
  2. [Z]为Web程序员解毒:9个IE常见Bug的解决方案
  3. 【Python】Matplotlib 可视化必备神书,附pdf下载
  4. Scala 类中声明方法
  5. 多态部分作业 2.编写2个接口:InterfaceA和InterfaceB;在接口InterfaceA中有个方法void 输出大小写字母表
  6. 整合Tomcat和Nginx实现动静态负载均衡
  7. 设置在VS2005的IDE中迅速打开xaml文件
  8. 蓄水池抽样算法 Reservoir Sampling
  9. 关于ZooKeeper集群脑裂及其解决方案
  10. 虚拟服务器和虚拟主机(空间)的区别
  11. AAAI 2019 使用循环条件注意力结构探索回答立场检测任务
  12. 多个android客户端使用的数据库,android – 将Firebase数据库与本地数据库一起使用...
  13. U8恢复记账操作步骤
  14. 2023最新SSM计算机毕业设计选题大全(附源码+LW)之java文创产品推荐系统设计与实现95ml5
  15. 系统映像恢复计算机重启失败,学会使用win10系统的winRE进行系统启动修复、系统还原、系统重置、系统映像恢复等-网络教程与技术 -亦是美网络...
  16. 微信记录删了,怎么恢复找回来?5种攻略推荐
  17. 匈牙利算法(Hungarian algorithm)
  18. 如何理解电容器容抗等效
  19. 微信开放平台开源_开源需要开放徽章的3个原因
  20. ArcEngine编辑模块——将线段按距离、按比例分割成N条线段

热门文章

  1. vue 3.4x以上如何改变项目运行端口号
  2. [编程入门]带参数宏定义练习:定义一个带参的宏,使两个参数的值互换,并写出程序,输入两个数作为使用宏时的实参。输出已交换后的两个值。
  3. 来自一位家长的肺腑之言,句句在理!!!
  4. 比特(bit)和字节(byte)(1byte=8bit)
  5. React中BrowserRouter与HashRouter的区别
  6. 打开数据库_数据库客户端navicat遇到问题怎么办?
  7. ssh无密码登陆权威指南
  8. RabbitMQ--topic
  9. maven配置junit5_JUnit 5和Selenium –改善项目配置
  10. 后台审核管理 ergo_Kogito,ergo规则—第2部分:规则的全面执行模型