Spring3.2.0和Quartz1.8.6集群配置

jopen 11年前發布 | 58K 次閱讀 Spring Quartz 作業調度框架

最近項目中要添加一個后臺任務處理的功能,要求做到集群,然后就調研了很多,網上也有好多資料,但在項目中應用時還是有很多問題,最終也找到了解決辦法,以下是完整實現。

首先是任務實現類,一個普通的service或bean:

public class EventMonitorService implements Serializable {
    private static final long serialVersionUID = 7026615035981953235L;

    private static final Logger LOG = LoggerFactory
            .getLogger(EventMonitorService.class);
        @Autowired
    private EventDao eventDao;
        @Autowired
    private SessionFactory sessionFactory;

    /**
     * 定時監控方法
     */
    public void startMonitorEvent() {
        LOG.debug("開始執行定時任務--監控Event超時");
        //自己的業務處理
    }
}
第二步,創建任務代理類DetailQuartzJobBean
import java.lang.reflect.Method;

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

import com.telematics.tsp.util.SpringContextKit;

public class DetailQuartzJobBean extends QuartzJobBean {
    private static final Logger logger = LoggerFactory
            .getLogger(DetailQuartzJobBean.class);
    private String targetObject;
    private String targetMethod;
    private final ApplicationContext applicationContext;

    public DetailQuartzJobBean() {
        this.applicationContext = SpringContextKit.ME.getApplicationContext();
    }

    @Override
    protected void executeInternal(JobExecutionContext context)
            throws JobExecutionException {
        try {
            Object otargetObject = applicationContext.getBean(targetObject);
            System.out.println(otargetObject.toString());
            Method m = null;
            try {
                m = otargetObject.getClass().getMethod(targetMethod,
                        new Class[] {});
                m.invoke(otargetObject, new Object[] {});
            } catch (SecurityException e) {

            } catch (NoSuchMethodException e) {

            }
        } catch (Exception e) {
            throw new JobExecutionException(e);
        }
    }

    public void setTargetObject(String targetObject) {
        this.targetObject = targetObject;
    }

    public void setTargetMethod(String targetMethod) {
        this.targetMethod = targetMethod;
    }
}

這里在獲取applicationContext時視項目框架而定,就是獲得應用上下文。

第三步,配置quartz.properties

#============================================================================
# Configure Main Scheduler Properties  
#============================================================================
org.quartz.scheduler.instanceName = EventScheduler   
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
 

#============================================================================
# Configure JobStore  
#============================================================================
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
# mysql
#org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
# Oracle
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.oracle.OracleDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.maxMisfiresToHandleAtATime=10
org.quartz.jobStore.isClustered = true  
org.quartz.jobStore.clusterCheckinInterval = 20000 

第四步,配置quartz.xml

<?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"
    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">
    <!-- 要調用的工作類 -->
    <bean id="eventMonitorService" class="demo.EventMonitorService"></bean>


    <!-- 定義任務 -->
    <bean id="vcaEventJobTask" class="org.springframework.scheduling.quartz.JobDetailBean">
        <property name="jobClass">
            <!-- 上面的任務代理類 -->
            <value>com.tservice.vca.jobtask.DetailQuartzJobBean</value>
        </property>
        <property name="jobDataAsMap">
            <map>
                <!-- 實際的任務的Bean name,填上EventMonitorService的Bean name -->
                <entry key="targetObject" value="eventMonitorService" />
                <!-- 執行Bean中的哪個方法 -->
                <entry key="targetMethod" value="startMonitorEvent" />
            </map>
        </property>
    </bean>

    <!-- 任務觸發器 -->
    <bean id="eventTaskTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <!-- 任務代理Bean name -->
            <ref bean="vcaEventJobTask" />
        </property>
        <property name="cronExpression">
            <!-- 配置表達式,這里表示每五分鐘執行一次 -->
            <value>0 0/5 * * * ?</value>
        </property>
    </bean>
    <!-- 任務調度入口 -->
    <bean autowire="no"
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <!-- 任務列表,可以配置多個任務加入到該List -->
        <property name="triggers">
            <list>
                <ref local="eventTaskTrigger" />
            </list>
        </property>
        <property name="configLocation" value="classpath:quartz.properties" />
    </bean>
</beans>
接下來就可以正常啟動你的項目了。


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!