Quartz任務監控管理(轉)

 

應網友sohuexe的要求,做一個Quartz任務監控管理,類似Windows任務管理器,可以獲得運行時的實時監控,查看任務運行狀態,動態增加任務,暫停、恢復、移除任務等。對於動態增加任務,可以參加我的前一篇文章《Quartz如何在Spring動態配置時間》,本文在前文的基礎上擴展,增加暫停、恢復、移除任務等功能,實現Quartz任務監控管理。

我將其發佈到Aptana Cloud中,可以瀏覽http://monitorquartz.aptanacloud.com查看效果。

先看一下最終實現實現效果,只有兩個頁面 ,如下

在這個頁面查看任務實時運行狀態,可以暫停、恢復、移除任務等


在這個頁面可以動態配置調度任務。


實現任務監控,必須能將數據持久化,這裏採用數據庫方式,Quartz對任務的數據庫持久化有着非常好的支持。我在這裏採用quartz 1.6.5,在Quartz發行包的docs/dbTables目錄包含有各種數據庫對應腳本,我用的是MySql 5.0,所以選用tables_mysql_innodb.sql建表。

建表完成後,配置數據庫連接池,分兩步:
1、配置jdbc.properties文件
Java代碼
jdbc.driverClassName=com.mysql.jdbc.Driver   
jdbc.url=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true   
jdbc.username=root   
jdbc.password=kfs  

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/quartz?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true
jdbc.username=root
jdbc.password=kfs

2.配置applicationContext.xml文件
Java代碼
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
    <property name="locations">   
            <list>   
                <value>classpath:jdbc.properties</value>   
            </list>   
        </property>   
</bean>   
      
    <!-- 數據源定義,使用c3p0 連接池 -->   
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">   
    <property name="driverClass" value="${jdbc.driverClassName}" />      
    <property name="jdbcUrl" value="${jdbc.url}" />      
    <property name="user" value="${jdbc.username}" />   
    <property name="password" value="${jdbc.password}" />        
    <property name="initialPoolSize" value="${cpool.minPoolSize}"/>      

    <property name="minPoolSize" value="${cpool.minPoolSize}" />     
    <property name="maxPoolSize" value="${cpool.maxPoolSize}" />     
    <property name="acquireIncrement" value="${cpool.acquireIncrement}" />   
    <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>      
</bean>  

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
                        <list>
                                <value>classpath:jdbc.properties</value>
                        </list>
                </property>
</bean>
       
        <!-- 數據源定義,使用c3p0 連接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClassName}" />       
        <property name="jdbcUrl" value="${jdbc.url}" />       
        <property name="user" value="${jdbc.username}" />       
        <property name="password" value="${jdbc.password}" />               
        <property name="initialPoolSize" value="${cpool.minPoolSize}"/>       
        <property name="minPoolSize" value="${cpool.minPoolSize}" />       
        <property name="maxPoolSize" value="${cpool.maxPoolSize}" />       
        <property name="acquireIncrement" value="${cpool.acquireIncrement}" />
    <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>   
</bean>

配置Quartz,也分兩步
1、配置quartz. properties
Java代碼
…   
org.quartz.jobStore.misfireThreshold = 60000  
#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  
org.quartz.jobStore.tablePrefix = QRTZ_     
org.quartz.jobStore.isClustered = false  org.quartz.jobStore.maxMisfiresToHandleAtATime=1  


org.quartz.jobStore.misfireThreshold = 60000
#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
org.quartz.jobStore.tablePrefix = QRTZ_  
org.quartz.jobStore.isClustered = false  org.quartz.jobStore.maxMisfiresToHandleAtATime=1

在這裏採用JobStoreTX,將任務持久化到數據中,而不再是簡單的內存方式:RAMJobStore

2、配置applicationContext-quartz.xml
Java代碼
<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">   
        <property name="dataSource" ref ="dataSource" />         
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>   
        <property name="configLocation" value="classpath:quartz.properties"/>   
    </bean>   
      
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">   
        <property name="jobClass">   
            <value>   
                com.sundoctor.example.service.MyQuartzJobBean   
            </value>   
        </property>   
        <property name="jobDataAsMap">   
            <map>   
                <entry key="simpleService">   
                    <ref bean="simpleService"/>   
                </entry>   
            </map>   
        </property>      
</bean>  

<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="dataSource" ref ="dataSource" />      
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
        <property name="configLocation" value="classpath:quartz.properties"/>
    </bean>
   
<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass">
            <value>
                com.sundoctor.example.service.MyQuartzJobBean
            </value>
        </property>
        <property name="jobDataAsMap">
            <map>
                <entry key="simpleService">
                    <ref bean="simpleService"/>
                </entry>
            </map>
        </property>   
</bean>

到些,相關配置全部完成,對於配置的具體描述,可以參加我的前一篇文章《Quartz如何在Spring動態配置時間》

實現任務動態添加配置

請參考com.sundoctor.quartz.service.SchedulerServiceImpl.java中的各種schedule方法,在《Quartz如何在Spring動態配置時間》有具體描述。在這裏說一下:
添加一個Job在表qrtz_job_details插入一條記錄
添加一個Simple Trigger在表qrtz_simple_triggers插入一條記錄
添加一個Cron Trigger 在表qrtz_cron_triggers插入一條記錄
添加Simple Trigger和Cron Trigger都會同進在表qrtz_triggers插入一條記錄,開始看的第一個頁面調度任務列表數據就是從qrtz_triggers表獲取

實現任務實時監控,暫停、恢復、移除任務等
在com.sundoctor.quartz.service.SchedulerServiceImpl.java類中

暫停任務
Java代碼
public void pauseTrigger(String triggerName,String group){         
        try {   
            scheduler.pauseTrigger(triggerName, group);//停止觸發器   
        } catch (SchedulerException e) {   
            throw new RuntimeException(e);   
        }   
}  

public void pauseTrigger(String triggerName,String group){               
                try {
                        scheduler.pauseTrigger(triggerName, group);//停止觸發器
                } catch (SchedulerException e) {
                        throw new RuntimeException(e);
                }
}

恢復任務
Java代碼
public void resumeTrigger(String triggerName,String group){        
        try {   
            scheduler.resumeTrigger(triggerName, group);//重啓觸發器   
        } catch (SchedulerException e) {   
            throw new RuntimeException(e);   
        }   
    }  

public void resumeTrigger(String triggerName,String group){               
                try {
                        scheduler.resumeTrigger(triggerName, group);//重啓觸發器
                } catch (SchedulerException e) {
                        throw new RuntimeException(e);
                }
        }

移除任務
Java代碼
public boolean removeTrigdger(String triggerName,String group){        
        try {   
            scheduler.pauseTrigger(triggerName, group);//停止觸發器   
            return scheduler.unscheduleJob(triggerName, group);//移除觸發器   
        } catch (SchedulerException e) {   
            throw new RuntimeException(e);   
        }   
    }  

public boolean removeTrigdger(String triggerName,String group){               
                try {
                        scheduler.pauseTrigger(triggerName, group);//停止觸發器
                        return scheduler.unscheduleJob(triggerName, group);//移除觸發器
                } catch (SchedulerException e) {
                        throw new RuntimeException(e);
                }
        }


其它類的實現請參加《Quartz如何在Spring動態配置時間》,那裏有具體說明。

到此,基本簡單實現了Quartz任務監控管理。其實面這裏只是實現了Trigger任務的監控管理,沒有實現Job任務的監控管理,實現Job任務的監控管理跟Trigger差不多。用Quartz可以很方便實現多樣化的任務監控管理,Trigger任務和Job任務都可進行分組管理。

Quartz很強大,也很簡單,只有想不到的,沒有做不到的,人有多大膽,地有多高產。

有網友問題:
發表時間:2009-08-09 我的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 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-2.0.xsd">

<bean id="articleBS" class="com.cms.article.service.impl.ArticleBS">
<property name="tarticleDAO">
<ref bean="article.tarticleDAO" />
</property>
</bean>

<bean name="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
</bean>

<bean id="jobDetail" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass">
<value>com.cms.quartzpublic.job.ArticleQuartzJobBean</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="articleBS">
<ref local="articleBS" />
</entry>
</map>
</property>

</bean>

<!-- cms 定時發佈文章模塊service層ioc及事務配置 start -->
<bean id="articleQuartzBS" lazy-init="true"
class="com.cms.quartzpublic.serivce.impl.ArticleQuartzBS">

        <property name="articleQuartzDAO">
<ref bean="article.articleQuartzDAO" />
</property>

        
        <property name="scheduler">
        <ref bean="quartzScheduler" />
        </property>
<property name="jobDetail">
<ref bean="jobDetail" />
        </property>
        
</bean>
     
    <bean id="article.quartzBSTrans" parent="cmsBaseTransationProxy">
<property name="target">
<ref local="articleQuartzBS" />
</property>
</bean>
<!-- cms 定時發佈文章模塊service層ioc及事務配置 end -->
</beans>

ArticleQuartzJobBean 類如下
package com.cms.quartzpublic.job;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Trigger;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.cms.article.service.IArticleBS;
import com.cms.article.service.impl.ArticleBS;
import com.cms.article.vo.TarticleVO;
import com.cms.po.Tarticle;
import com.cms.quartzpublic.serivce.impl.ArticleQuartzBS;

public class ArticleQuartzJobBean extends QuartzJobBean {

private ArticleBS articleBS;


public void setArticleBS(ArticleBS articleBS) {
this.articleBS = articleBS;
}


@Override
protected void executeInternal(JobExecutionContext jobexecutioncontext)
throws JobExecutionException {
Trigger trigger = jobexecutioncontext.getTrigger();
String triggerName = trigger.getName();
String group = trigger.getGroup();
String[] triggerNameArray = triggerName.split("//$");
String articleId = triggerNameArray[1];
try {
TarticleVO tarticleVO = articleBS.lookArticleById(articleId);
String fileNamePath = articleBS.createHtmlDir(tarticleVO, tarticleVO.getChannleName());
String articlehref = articleBS.jspTOhtml(fileNamePath,"",tarticleVO);
if(articlehref != null && !articlehref.equals("")){
tarticleVO.setArticlehref(articlehref);
Tarticle tarticle2 = articleBS.saveOrUpdateArticle(tarticleVO);
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
private ArticleBS articleBS;這個一直是null值
這個articleBS實現了序列化接口了。。。。
問題在哪裏。。。。。鬱悶了,盼解決
解答:
不但com.cms.article.service.impl.ArticleBS要實現Serializable序列化接口,其中注入的article.tarticleDAO也必須實現實現Serializable序列化接口。



com.cms.quartzpublic.job.ArticleQuartzJobBean類被序列化保存到數據庫表qrtz_job_details的job_class_name字段中,quartz在運行時會讀取qrtz_job_details表中的job_class_name將其反序列化。這也是爲什麼com.cms.article.service.impl.ArticleB和其中注入各屬性需要實現Serializable序列化接口的原因,所以你每次修改ArticleQuartzJobBean類或者其中的articleBS都要刪除qrtz_job_details表對應的job記錄,否則可能會出現空指針異常,因爲你如果你沒有刪除qrtz_job_details表中的記錄,你修改的東東並不會自動更新到qrtz_job_details中,你用的還是原來舊版本的ArticleQuartzJobBean類。

oracle 需要修改quartz. properties 文件將
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
改爲
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.oracle.OracleDelegate

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章