Quartz定時任務簡單實例


文章綱要:

初步搭建一個由Quartz為引擎集群的定時任務模塊,功能為每隔30秒打印一條信息(Hello World!!!)

一、環境

  • Spring MVC 
  • Mevan
  • Quartz 2.2.1

二、簡介

  Quartz是一個完全由java編寫的開源作業調度框架。不要讓作業調度這個術語嚇着你。盡管Quartz框架整合了許多額外功能, 但就其簡易形式看,你會發現它易用得簡直讓人受不了!。簡單地創建一個實現org.quartz.Job接口的java類。Job接口包含唯一的方法:

  public void execute(JobExecutionContext context)throws JobExecutionException;

  在你的Job接口實現類里面,添加一些邏輯到execute()方法。一旦你配置好Job實現類並設定好調度時間表,Quartz將密切注意剩余時間。當調度程序確定該是通知你的作業的時候,Quartz框架將調用你Job實現類(作業類)上的execute()方法並允許做它該做的事情。無需報告任何東西給調度器或調用任何特定的東西。僅僅執行任務和結束任務即可。如果配置你的作業在隨后再次被調用,Quartz框架將在恰當的時間再次調用它

三、搭建環境

1、配置Mevan節點,下載Jar包。在pom.xml文件里加上如下代碼:

目前最新版本是2.2.1(2016.11)

<dependency>
    <groupId>org.quartz-scheduler</groupId>
    <artifactId>quartz</artifactId>
    <version>2.2.1</version>
</dependency>

 

2、在applicatonContext.xm里增加資源引用加入如下代碼:

(quartz.xml為定時任務配置文件,Quartz可以使用配置文件形式管理觸發,也可以完全使用Java代碼控制觸發。使用配置文件好處是可以減少代碼開發量,如有修改不需要編譯Java類。)

<import resource="quartz.xml"/> 

 

3.編寫quartz.xml,每個節點有詳細的解釋,看代碼即可,將其放到src\main\resources

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context.xsd  
            http://www.springframework.org/schema/jdbc  
            http://www.springframework.org/schema/jdbc/spring-jdbc.xsd  
            http://www.springframework.org/schema/jee 
            http://www.springframework.org/schema/jee/spring-jee.xsd  
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx.xsd  
            http://www.springframework.org/schema/util  
            http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 將任務加載到quartz配置中 --> 
    <bean id="taskJob"
        class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
        <!-- 任務完成之后是否依然保留到數據庫,默認false -->
        <property name="durability" value="true" />
        <property name="requestsRecovery" value="true" />
        <!-- 任務的實現類,必須 -->
        <property name="jobClass">
            <value>com.myTest.quartz.CommJobBean</value>
        </property>
        <!-- 用來給作業提供數據支持的數據結構 -->
        <property name="jobDataAsMap">
            <map>
                <entry key="targetObject" value="commJob" /><!-- 調用的類 -->
                <entry key="targetMethod" value="sjcq" /><!-- 調用類中的方法 -->
            </map>
        </property>
        <property name="description" value="通用信息任務" />
    </bean>

    <!-- 定義觸發時間 -->
    <bean id="taskTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <!-- 觸發器與任務綁定 -->
        <property name="jobDetail" ref="taskJob" />
        <property name="cronExpression" value="0/30 * * * * ?" /><!-- 規則表達式 每隔30秒執行一次 -->
    </bean>
    
    <!-- 總管理類 如果將lazy-init='false'那么容器啟動就會執行調度程序  -->
    <bean id="taskScheduler" lazy-init="false" autowire="no"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean"
        destroy-method="destroy">
        <property name="overwriteExistingJobs" value="true" />
        <!-- 啟動延時 -->
        <property name="startupDelay" value="5" />
        <!-- 是否自動啟動 -->
        <property name="autoStartup" value="true" />
        <!-- 啟動的定時器 -->
        <property name="triggers">
            <list>
                <ref bean="taskTrigger" />
            </list>
        </property>

        <property name="applicationContextSchedulerContextKey" value="applicationContext" />
        <property name="configLocation" value="classpath:quartz.properties" />
    </bean>

</beans>

 

4.編寫quartz.properties文件。將其放到src\main\resources,如果每有特別的需求只需要更改數據庫連接屬性就可以了。

因為要部署到集群當中,一套服務程序要部署到多態服務器上,所以定時更新時容易造成沖突。比如,服務器1開始了定時任務TASK1,但是服務器2也開始了定時任務TASK1,這就造成了任務沖突,為了解決這個問題Quartz引入了幾張數據表作為執行標記。

 

大家可以去Quartz管網下載數據庫結構Sql腳本,執行一下建表就可以。目前最新版本是2.2.3。下面是下載地址

http://www.quartz-scheduler.org/downloads/

有其他博主研究了quartz.properties中的各個屬性,下面是地址。

http://blog.csdn.net/yixiaoping/article/details/10476817

 

 

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

#==============================================================
#Skip Check Update 
#update:true 
#not update:false 
#==============================================================
org.quartz.scheduler.skipUpdateCheck = true 

#==============================================================
#Configure ThreadPool 
#==============================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool 
org.quartz.threadPool.threadCount = 10 
org.quartz.threadPool.threadPriority = 5 
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true

#==============================================================
#Configure JobStore 
#==============================================================
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate  
org.quartz.jobStore.tablePrefix = QRTZ_ 
org.quartz.jobStore.maxMisfiresToHandleAtATime = 1 
org.quartz.jobStore.misfireThreshold = 120000 
org.quartz.jobStore.txIsolationLevelSerializable = true 
org.quartz.jobStore.selectWithLockSQL = SELECT * FROM {0}LOCKS WHERE LOCK_NAME = ? FOR UPDATE

org.quartz.jobStore.dataSource = myDS  
   
org.quartz.jobStore.isClustered = true 
org.quartz.jobStore.clusterCheckinInterval = 20000 

#===========================================================  
# Configure Datasources  
#===========================================================  
#org.quartz.dataSource.myDS.driver = oracle.jdbc.driver.OracleDriver  
#org.quartz.dataSource.myDS.URL = jdbc:oracle:thin:@10.19.22.79:1521:ljts  
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver  #注意:這里改成自己的數據庫驅動
org.quartz.dataSource.myDS.URL = jdbc:mysql://10.19.22.53:3306/test_db  #注意:這里改成自己的數據庫地址
org.quartz.dataSource.myDS.user = root  #注意:這里改成自己的數據庫用戶名
org.quartz.dataSource.myDS.password = root  #注意:自己的數據庫密碼
org.quartz.dataSource.myDS.maxConnections = 100  
org.quartz.dataSource.myDS.validationQuery=select 1 from dual  

#==============================================================
# Configure Plugins 
#==============================================================
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin  
org.quartz.plugin.shutdownhook.class = org.quartz.plugins.management.ShutdownHookPlugin 
org.quartz.plugin.shutdownhook.cleanShutdown = true 
 

 

  5編寫CommJobBean.java

package com.inspur.ljts.quartz;

import java.lang.reflect.Method;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

/** 
 * @ClassName CommJobBean 
 * @Description 公用任務
 * @version 1.0
 */
public class CommJobBean extends QuartzJobBean { 

    private String targetObject; 
    private String targetMethod; 
    private ApplicationContext ctx; 

    @Override  
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {  
    
        try {
            Object otargetObject = ctx.getBean(targetObject); 
            Method m = null; 
        
                try { 
                    m = otargetObject.getClass().getMethod(targetMethod); 
                    m.invoke(otargetObject); 
                } catch (SecurityException e) { 
                    e.printStackTrace(); 
                } catch (NoSuchMethodException e) { 
                    e.printStackTrace(); 
                } 
        } catch (Exception e) { 
            throw new JobExecutionException(e); 
        } 
    
    } 
    
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.ctx = applicationContext; 
    } 
    
    public void setTargetObject(String targetObject) { 
        this.targetObject = targetObject; 
    } 
    
    public void setTargetMethod(String targetMethod) {  
        this.targetMethod = targetMethod;  
    }  

}

 

  6.編寫具體業務類CommJob.java  

package com.xxx.task;

import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.rocketmq.client.exception.MQBrokerException;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.message.Message;
import com.alibaba.rocketmq.remoting.exception.RemotingException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xxx.comm.base.ICommService;
import com.xxx.comm.base.SjcqException;
import com.xxx.comm.consts.CommConsts;
import com.xxx.comm.context.SjcqContext;
import com.xxx.comm.sjcqTask.bean.SjcqTask;
import com.xxx.comm.sjcqTask.service.SjcqTaskService;
import com.xxx.comm.utils.JsonUtil;

/**
 * @ClassName TaskJob
 * @Description 數據抽取定時任務
 * @version 1.0
 */

@Component
@SuppressWarnings("rawtypes")
public class CommJob {

    public void sjcq() {
        
        System.out.println("Hello World!!!");    
    }
}

 

  7.將項目發布部署到Tomcat,啟動Tomcat,定時任務就會自動運行了。完畢!!!!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM