Spring+Quartz的集群配置

本文详细介绍如何在Spring框架中配置Quartz实现集群环境下的定时任务。从下载Quartz库到配置数据库连接池、设置集群参数,再到定义具体任务及触发器,最后提供测试方法验证配置正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、下载quartz-2.2.2

2、创建数据库表 

在数据库中建表。建表模版在Quartz包下quartz-2.2.2\docs\dbTables下,选择相应的数据库和版本

3、配置数据库连接池,如果spring已经配置则不需要再另行配置,只需在后面配置的spring-job.xml引入即可

 3.1、配置数据库连接池

   jdbc.properties

#jdbc
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/webdemo?useUnicode=true&characterEncoding=UTF8
jdbc.username=root
jdbc.password=root123

c3p0.pool.size.max=10
c3p0.pool.size.min=2
c3p0.pool.size.ini=3
c3p0.pool.size.increment=2
#hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
#hibernate cache
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml

    applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	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.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
	
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<!-- 扫描service自动注入为bean -->
	<context:component-scan base-package="com.tzz.web,com.tzz.hessian.service,com.tzz.aop,com.tzz.job.springtask" />
	
	<!-- 配置数据源 c3p0 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 请求超时时间 -->
		<property name="checkoutTimeout" value="30000" />
		<!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
		<property name="idleConnectionTestPeriod" value="30" />
		<!-- 连接数据库连接池最大空闲时间 -->
		<property name="maxIdleTime" value="30" />
		<!-- 连接池初始化连接数 -->
		<property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
		<property name="minPoolSize" value="${c3p0.pool.size.min}" />
		<property name="maxPoolSize" value="${c3p0.pool.size.max}" />
		<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
		<property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
	</bean>

</beans>

 3.2、 配置quartz.properties 

#==============================================================  
#Configure Main Scheduler Properties  
#==============================================================   
org.quartz.scheduler.instanceName = TestScheduler1
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.JobStoreTX
org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.tablePrefix = QRTZ_
org.quartz.jobStore.maxMisfiresToHandleAtATime=10
org.quartz.jobStore.isClustered = true  
org.quartz.jobStore.clusterCheckinInterval = 20000  

# Using datasource
org.quartz.jobStore.dataSource = qzDS

#Define the datasource to use
org.quartz.dataSource.qzDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL = jdbc:mysql://localhost:3306/webdemo?useUnicode=true&amp;characterEncoding=UTF8
org.quartz.dataSource.qzDS.user = root
org.quartz.dataSource.qzDS.password = root123
org.quartz.dataSource.qzDS.maxConnections = 30

说明:

org.quartz.scheduler.instanceName属性可为任何值,用在 JDBC JobStore 中来唯一标识实例,但是所有集群节点中必须相同。   

org.quartz.scheduler.instanceId 属性为 AUTO即可,基于主机名和时间戳来产生实例 ID。   

org.quartz.jobStore.class属性为 JobStoreTX,将任务持久化到数据中。因为集群中节点依赖于数据库来传播 Scheduler 实例的状态,你只能在使用 JDBC JobStore 时应用 Quartz 集群。

这意味着你必须使用 JobStoreTX 或是 JobStoreCMT 作为 Job 存储;你不能在集群中使用 RAMJobStore。   

org.quartz.jobStore.isClustered 属性为 true,你就告诉了 Scheduler 实例要它参与到一个集群当中。这一属性会贯穿于调度框架的始终,用于修改集群环境中操作的默认行为。   

org.quartz.jobStore.clusterCheckinInterval 属性定义了Scheduler 实例检入到数据库中的频率(单位:毫秒)。Scheduler 检查是否其他的实例到了它们应当检入的时候未检入;

这能指出一个失败的 Scheduler 实例,且当前 Scheduler 会以此来接管任何执行失败并可恢复的 Job。通过检入操作,Scheduler 也会更新自身的状态记录。

clusterChedkinInterval 越小,Scheduler 节点检查失败的 Scheduler 实例就越频繁。默认值是 15000 (即15 秒)。  

4、定义任务类

package com.tzz.job.quartz;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
/**
 * 通过extends QuartzJobBean 的方式
 *
 */
public class EXQuartzJob extends QuartzJobBean {

	protected final transient Logger log = Logger.getLogger(EXQuartzJob.class);

	@SuppressWarnings("unused")
	private int timeout;
	@SuppressWarnings("unused")
	private static int i = 0;

	// 调度工厂实例化后,经过timeout时间开始执行调度
	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	@Override
	protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
		log.info("***Quartz定时任务执行中***通过extends QuartzJobBean 的方式***");
	}

}

 spring-job.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:task="http://www.springframework.org/schema/task"
	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.1.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.1.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/task 
		http://www.springframework.org/schema/task/spring-task-4.1.xsd
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">

	<bean name="exQuartzJob"
		class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
		<property name="jobClass" value="com.tzz.job.quartz.EXQuartzJob" />
		<property name="jobDataAsMap">
			<map>
				<entry key="timeout" value="0" />
			</map>
		</property>
	</bean>
	<bean id="exQuartzJobCronTrigger"
		class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="exQuartzJob" />
		<!-- 每5秒执行一次 -->
		<property name="cronExpression" value="0/10 * * * * ?" />
	</bean>

	<!-- 配置调度工厂 -->
	<bean name="schedulerFactory" lazy-init="false"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		
		<!--集群配制start-->
		<property name="dataSource" ref="dataSource" />
        <property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>  
        <property name="configLocation" value="classpath:quartz.properties"/>   
		<!-- 集群配制 end -->
		
		<property name="triggers">
			<list>
				<ref bean="exQuartzJobCronTrigger" />
			</list>
		</property>
	</bean>	
</beans>

测试:

public static void main(String[] args) {
		System.out.println("Test start.");
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
context.getBean("schedulerFactory");
		System.out.print("Test end..");
}

动态修改执行时间无需重启
1.更改表qrtz_cron_triggers的cronExpression(定时任务时间)
2.将表qrtz_triggers的NEXT_FIRE_TIME(下一次执行时间)和PREV_FIRE_TIME(上一次执行时间)的值改为0

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值