spring quartz2.2.1 cluster

1 篇文章 0 订阅
1 篇文章 0 订阅

quartz 持久化介绍

1 大家都清楚quartz最基本的概念就是job,在job内调用具体service完成具体功能,quartz需要把每个job存储起来,方便调度,quartz存储job方式就分三种,我们最常用的也是quartz默认的是RAMJobStore,RAMJobStore顾名思义就是把job的相关信息存储在内存里,如果用spring配置quartz的job信息的话,所有信息是配置在xml里,当spirng context启动的时候就把xml里的job信息装入内存。这一性质就决定了一旦JVM挂掉或者容器挂掉,内存中的job信息就随之消失,无法持久化。另外两种方式是JobStoreTX和JobStoreCMT,暂时不讨论这两者的区别,使用这两种JobStore,quartz就会通过jdbc直连或者应用服务器jndi连接数据库,读取配置在数据库里的job初始化信息,并且把job通过java序列化到数据库里,这样就使得每个job信息得到了持久化,即使在jvm或者容器挂掉的情况下,也能通过数据库感知到其他job的状态和信息。 
 2 quartz集群各节点之间是通过同一个数据库实例(准确的说是同一个数据库实例的同一套表)来感知彼此的。 


quartz实现代码

1.新建quartz相关表
2.quartz.properties
#==============================================================  
#Configure Main Scheduler Properties  
#==============================================================   
org.quartz.scheduler.instanceName = DefaultQuartzScheduler
org.quartz.scheduler.instanceId = AUTO  

#==============================================================  
#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.misfireThreshold = 60000
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreCMT
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.maxMisfiresToHandleAtATime=10
org.quartz.jobStore.isClustered = true  
org.quartz.jobStore.clusterCheckinInterval = 20000  

3.spring-scheduler.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:task="http://www.springframework.org/schema/task"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
			http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
	default-lazy-init="true">
	<description>使用Spring的 Scheduled的定时任务配置</description>
    
     <!-- 注册调度任务 -->  
    <bean id="mapScheduler" lazy-init="false" autowire="no"   
             class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
        <property name="dataSource" ref="dataSource" />   
        <property name="triggers">  
                <list>  
                     <ref bean="testTrigger"/>  
                </list>  
        </property>  
        <property name="applicationContextSchedulerContextKey" value="applicationContext" />  
        <property name="configLocation" value="classpath:quartz.properties" />  
         <!--可选,QuartzScheduler启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 -->  
        <property name="overwriteExistingJobs" value="true" />  
        <!--设置自动启动 -->  
        <property name="autoStartup" value="true" /> 
    </bean>  
    
    <bean name="springCronJob" class="com.test.util.schedule.SpringCronJob"></bean>  
    <bean id="testSpringCronJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">  
        <property name="jobClass">  
                <value>com.test.util.schedule.MyDetailQuartzJobBean</value>  
        </property>  
        <property name="jobDataAsMap">  
                <map>  
                      <entry key="targetObject" value="springCronJob" />  
                      <entry key="targetMethod" value="pmenuCount" />  
                </map>  
        </property>  
        <property name="durability" value="true" />
    </bean>  
    <bean id="testTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">  
        <property name="jobDetail">  
                <ref bean="testSpringCronJob" />  
        </property>  
        <property name="cronExpression">  
       		<!-- 每次启动主线程的等待时间 时间顺序按 秒 分 时 日 月 周 年 当前为每30秒执行一次 -->
             <value>*/30 * * * * ?</value>  
        </property>  
    </bean>

</beans>



4.MyDetailQuartzJobBean.java

package com.test.util.schedule;

import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;  
import org.quartz.JobExecutionException;  
import org.springframework.context.ApplicationContext;  
import org.springframework.scheduling.quartz.QuartzJobBean;  
   
/** 
 * Spring调度任务 
 * @author admin
 * 
 */  
public class MyDetailQuartzJobBean extends QuartzJobBean {  
	/**
	 * 日志打印
	 */
	private static final Log log = LogFactory.getLog(MyDetailQuartzJobBean.class);
    	private String targetObject;    
    	private String targetMethod;    
    	private ApplicationContext applicationContext;   
    @Override  
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {  
     try {    
            Object otargetObject = applicationContext.getBean(targetObject);    
            Method m = null;    
            try {    
                m = otargetObject.getClass().getMethod(targetMethod, new Class[] {JobExecutionContext.class});    
                m.invoke(otargetObject, new Object[] {context});    
            } catch (SecurityException e) {    
            	log.info(e.getMessage());    
            } catch (NoSuchMethodException e) {    
            	log.info(e.getMessage());  
            }    
        } catch (Exception e) {    
            throw new JobExecutionException(e);    
        }    
    }  
    public void setApplicationContext(ApplicationContext applicationContext) {    
        this.applicationContext = applicationContext;    
    }    
    public void setTargetObject(String targetObject) {    
        this.targetObject = targetObject;    
    }    
    
    public void setTargetMethod(String targetMethod) {    
        this.targetMethod = targetMethod;    
    }    
}  

5. SpringCronJob.java

package com.test.util.schedule;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.test.service.PMenuService;

@Component 
public class SpringCronJob{

	private static final Log log = LogFactory.getLog(SpringCronJob.class);

	@Autowired
	private PMenuService pmService;
	
	/**
	 * 定时打印
	 */
	public void pmenuCount(JobExecutionContext context){
		log.info("执行结果为:" + pmService.count());
	}
}


注:

本文实现基于spirng4.0以上版本,quartz-2.2.1版本,低版本的quartz需要的spring版本也不同,否则会出现各种错误





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值