Quartz學習——Spring和Quartz集成詳解(三)

Spring是一個很優秀的框架,它無縫的集成了Quartz,簡單方便的讓企業級應用更好的使用Quartz進行任務的調度。下面就對Spring集成Quartz進行簡單的介紹和示例講解!和上一節 Quartz學習——二、簡單入門示例Demo
的流程類似,介紹Spring和Quartz集成存儲方式使用的是RAM方式和JDBC方式!
:在企業級開發過程當中,正常狀況下不會使用RAM方式進行任務的存儲,都是使用JDBC方式。方便學習,這兩種方式都進行介紹!
本篇中的代碼下載地址:spring_quartz demojava

一. Jar包依賴
使用Maven進行Jar包的管理,使用的jar包以下:mysql

<!-- quartz 的jar -->
    <dependency>
         <groupId>org.quartz-scheduler</groupId>
         <artifactId>quartz</artifactId>
         <version>2.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz-jobs</artifactId>
        <version>2.2.1</version>
    </dependency>
    <!-- spring相關jar -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>3.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>4.0.5.RELEASE</version>
        </dependency>
    
    <!-- 日誌相關jar包 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency><!--   Failed to load class "org.slf4j.impl.StaticLoggerBinder". -->
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.13</version>
    </dependency>
    <!-- MySql的包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.31</version>
    </dependency>

二.任務類Jobgit

package com.dufy.spring.quartz.chapter01.job;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Spring 整合 Quartz 的  Hello World!
 * @author dufy
 * @date 2017.02.26
 *
 */
public class HelloWorldJob implements Job{

    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        log.info("This is a first spring combine quartz !");
        log.info("Welcome to Spring_Quartz World!"+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
        log.info("Let's begin ! \n \n");
    }

}

測試類:github

package com.dufy.spring.quartz.chapter01.job;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HWTest {

    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring_quartz.xml");

        
    }
}

三.配置文件 spring_quartz.xml和運行結果spring

1:RAM存儲方式的xml配置文件sql

(1):配置文件數據庫

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 
        Spring整合Quartz進行配置遵循下面的步驟:
        1:定義工做任務的Job
        2:定義觸發器Trigger,並將觸發器與工做任務綁定
        3:定義調度器,並將Trigger註冊到Scheduler
     -->
    <!-- 1:定義任務的bean ,這裏使用JobDetailFactoryBean,也可使用MethodInvokingJobDetailFactoryBean ,配置相似-->
    <bean name="hwJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <!-- 指定job的名稱 -->
        <property name="name" value="hw_job"/>
        <!-- 指定job的分組 -->
        <property name="group" value="hw_group"/>
        <!-- 指定具體的job類 -->
        <property name="jobClass" value="com.dufy.spring.quartz.chapter01.job.HelloWorldJob"/>
        <!-- 必須設置爲true,若是爲false,當沒有活動的觸發器與之關聯時會在調度器中會刪除該任務  -->
        <property name="durability" value="true"/>
        <!-- 指定spring容器的key,若是不設定在job中的jobmap中是獲取不到spring容器的 -->
        <property name="applicationContextJobDataKey" value="applicationContext"/>
    </bean>
    <!-- 2.1:定義觸發器的bean,定義一個Simple的Trigger,一個觸發器只能和一個任務進行綁定 -->
    <!-- <bean name="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
        指定Trigger的名稱
        <property name="name" value="hw_trigger"/>
        指定Trigger的名稱
        <property name="group" value="hw_trigger_group"/>
        指定Tirgger綁定的Job
        <property name="jobDetail" ref="hwJob"/>
        指定Trigger的延遲時間 1s後運行
        <property name="startDelay" value="1000"/>
        指定Trigger的重複間隔  5s
        <property name="repeatInterval" value="5000"/>
        指定Trigger的重複次數
        <property name="repeatCount" value="5"/>
    </bean> -->
    
    <!-- 2.2:定義觸發器的bean,定義一個Cron的Trigger,一個觸發器只能和一個任務進行綁定 -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <!-- 指定Trigger的名稱 -->
        <property name="name" value="hw_trigger"/>
        <!-- 指定Trigger的名稱 -->
        <property name="group" value="hw_trigger_group"/>
        <!-- 指定Tirgger綁定的Job -->
        <property name="jobDetail" ref="hwJob"/>
        <!-- 指定Cron 的表達式 ,當前是每隔1s運行一次 -->
        <property name="cronExpression" value="0/1 * * * * ?" />
    </bean>
    
    
    <!-- 3.定義調度器,並將Trigger註冊到調度器中 -->
    <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <!-- <ref bean="simpleTrigger"/> -->
                <ref bean="cronTrigger"/>
            </list>
        </property>
        <!-- <property name="autoStartup" value="true" /> -->
    </bean>
    
</beans>

(2):運行結果編程

下圖爲Cron的Trigger運行結果,Simple的Trigger運行結果,能夠自行進行查看:
這裏寫圖片描述api

2:JDBC存儲方式的xml配置文件app

(1):配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <!-- =========JDBC版=========== -->
    <!-- 
        持久化數據配置,須要添加quartz.properties
     -->
    <bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
        <property name="configLocation" value="classpath:quartz.properties"/>   
    </bean>
    
</beans>

(2):quartz.properties

# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#

#============================================================================
# Configure Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName: dufy_test
org.quartz.scheduler.instanceId = AUTO

org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 2
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000
#============================================================================
# Configure JobStore
#============================================================================
 
#default config
#org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore
#持久化配置
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass:org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:true

#============================================================================
#havent cluster spring
#============================================================================
org.quartz.jobStore.isClustered = false  

#數據庫表前綴
org.quartz.jobStore.tablePrefix:qrtz_
org.quartz.jobStore.dataSource:qzDS

#============================================================================
# Configure Datasources
#============================================================================
#JDBC驅動
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://localhost:3306/quartz_test
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:root
org.quartz.dataSource.qzDS.maxConnection:10

(3):HelloWorldJob.java沒有改動,HWTest.java修改以下

package com.dufy.spring.quartz.chapter01.job;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HWTest {
    
     private static Scheduler scheduler;
     
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring_quartz.xml");

         scheduler = (StdScheduler)ac.getBean("scheduler");
         
         startSchedule();
    }
    
    public static void startSchedule() {
        try {
            // 一、建立一個JobDetail實例,指定Quartz
            JobDetail jobDetail = JobBuilder.newJob(HelloWorldJob.class)
            // 任務執行類
                    .withIdentity("job1_1", "jGroup1")
                    // 任務名,任務組
                    .build();
            
            // 觸發器類型
            //SimpleScheduleBuilder builder = SimpleScheduleBuilder
                    // 設置執行次數
                    //.repeatSecondlyForTotalCount(5);
        
            CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule("0/2 * * * * ?");
            // 二、建立Trigger
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity("trigger1_1", "tGroup1").startNow()
                    .withSchedule(builder)
                    .build();
            
            // 三、建立Scheduler
            scheduler = StdSchedulerFactory.getDefaultScheduler();
            scheduler.start();
            // 四、調度執行
            scheduler.scheduleJob(jobDetail, trigger);
            
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

}

使用的Cron類型的觸發進行存儲,運行期間能夠在數據庫查看到指定的任務已經保存到數據庫,並看到控制檯打印的信息!

(4):輸出的結果

這裏寫圖片描述

備註: 因爲本人能力有限,文中如有錯誤之處,歡迎指正。


謝謝你的閱讀,若是您以爲這篇博文對你有幫助,請點贊或者喜歡,讓更多的人看到!祝你天天開心愉快!


Java編程技術樂園:一個分享編程知識的公衆號。跟着老司機一塊兒學習乾貨技術知識,天天進步一點點,讓小的積累,帶來大的改變!

掃描關注,後臺回覆【祕籍】,獲取珍藏乾貨! 99.9%的夥伴都很喜歡

image.png | center| 747x519

© 天天都在變得更好的阿飛雲
相關文章
相關標籤/搜索