1.1 java中使用quartz
1.1.1集成jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xiao.it</groupId>
<artifactId>testJob</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<springframework.version>4.1.3.RELEASE</springframework.version>
<quartz.version>2.2.1</quartz.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Transaction dependency is required with Quartz integration -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Quartz framework -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
1.1.2创建job相关的类
public class HelloQuatzJob implements Job{
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
System.out.println("定时任务执行时间 "+new Date());
}
}
1.1.3调用类
public class TestJob {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory chedule=new StdSchedulerFactory();
Scheduler scheduler = chedule.getScheduler();
//定义一个任务
JobDetail detail=JobBuilder.
newJob(HelloQuatzJob.class)
.withIdentity("testjob1", "group1")
.build();
Date runTime = DateBuilder.evenSecondDateAfterNow();
//定义一个触发器
Trigger trigger=TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
.startAt(runTime)//设置触发开始时间
.withSchedule(
SimpleScheduleBuilder.repeatSecondlyForever(2)
.withIntervalInSeconds(2)//时间间隔
).build();
scheduler.scheduleJob(detail, trigger);
scheduler.start();
}
}
1.1.4结果图
1.2 spring集成quartz
1.2.1集成jar包同1.1.1
1.2.2创建简单job
public class SimpleSpringQuatz {
public void printJob(){
System.out.println("定时任务执行时间 "+new Date());
}
}
1.2.3创建复杂job
public class ComplexSchejob extends QuartzJobBean{
private ComplexJobClasExe complexBean;
@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
// TODO Auto-generated method stub
complexBean.print();
}
public ComplexJobClasExe getComplexBean() {
return complexBean;
}
public void setComplexBean(ComplexJobClasExe complexBean) {
this.complexBean = complexBean;
}
}
public class ComplexJobClasExe {
public void print(){
System.out.println("复杂任务:"+new Date());
}
}
1.2.4 spring中进行配置
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<bean id="simpleBean" class="testJob.SimpleSpringQuatz"></bean>
<bean id="complexBean" class="testJob.ComplexJobClasExe"></bean>
<bean id="simpleJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="simpleBean" />
<property name="targetMethod" value="printJob" />
</bean>
<bean id="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="testJob.ComplexSchejob" />
<property name="jobDataMap">
<map>
<entry key="complexBean" value-ref="complexBean" />
</map>
</property>
<property name="durability" value="true" />
</bean>
<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
<property name="jobDetail" ref="simpleJobDetail" />
<property name="startDelay" value="1000" />
<property name="repeatInterval" value="2000" />
</bean>
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="complexJobDetail" />
<property name="cronExpression" value="0/5 * * ? * *" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="jobDetails">
<list>
<ref bean="simpleJobDetail" />
<ref bean="complexJobDetail" />
</list>
</property>
<property name="triggers">
<list>
<ref bean="simpleTrigger" />
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>
1.2.5结果图
1.3 spring+quartz集群
1.3.1 建表
如上图所示从官网上下载quartz的包,找到对应的SQL并且执行对应的sql
生成quartz框架所需要的工作表。
1.3.2添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
1.3.3 添加配置spring-quartz.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<bean id="test" class="yonyou.worn.quartz.TestQuartJobClass"></bean>
<bean id="test1" class="yonyou.worn.quartz.TestQuartJobClass"></bean>
<bean id="TestjobTask" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="durability" value="true" />
<property name="jobClass">
<value>yonyou.worn.quartz.QuartJobClassBean</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="targetObject" value="test" />
<entry key="targetMethod" value="printjob" />
</map>
</property>
</bean>
<bean id="TestjobTask1" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="durability" value="true" />
<property name="jobClass">
<value>yonyou.worn.quartz.QuartJobClassBean</value>
</property>
<property name="jobDataAsMap">
<map>
<entry key="targetObject" value="test" />
<entry key="targetMethod" value="print" />
</map>
</property>
</bean>
<bean name="TestTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="TestjobTask" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean name="TestTrigger1" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="TestjobTask1" />
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean id="quartzScheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了 -->
<property name="overwriteExistingJobs" value="true" />
<!--必须的,QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动 -->
<property name="startupDelay" value="3" />
<!-- 设置自动启动 -->
<property name="autoStartup" value="true" />
<!-- 把spring上下 文以key/value的方式存放在了quartz的上下文中了 -->
<property name="applicationContextSchedulerContextKey" value="applicationContext" />
<!-- scheduler的名称 -->
<property name="schedulerName" value="ClusterScheduler" />
<property name="configLocation" value="classpath:resource/quartz.properties"/>
<property name="triggers">
<list>
<ref bean="TestTrigger" />
<ref bean="TestTrigger1" />
</list>
</property>
</bean>
</beans>
1.3.4 添加quartz.properties
#============================================================================
# Configure Main Scheduler Properties
#============================================================================
org.quartz.scheduler.instanceName: TestScheduler
org.quartz.scheduler.instanceId: AUTO
org.quartz.jobStore.clusterCheckinInterval=20000
org.quartz.scheduler.skipUpdateCheck: true
#============================================================================
# Configure ThreadPool
#============================================================================
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 3
org.quartz.threadPool.threadPriority: 5
#============================================================================
# Configure JobStore
#============================================================================
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class:org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
#org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
#org.quartz.jobStore.useProperties: false
#org.quartz.jobStore.dataSource: myDS
#org.quartz.jobStore.tablePrefix: QRTZ_
org.quartz.jobStore.isClustered: true
#============================================================================
# Configure Datasources
#============================================================================
#org.quartz.dataSource.myDS.driver: org.postgresql.Driver
#org.quartz.dataSource.myDS.URL: jdbc:postgresql://localhost/dev
#org.quartz.dataSource.myDS.user: jhouse
#org.quartz.dataSource.myDS.password:
#org.quartz.dataSource.myDS.maxConnections: 5
#============================================================================
# Configure Plugins
#============================================================================
##org.quartz.plugin.triggHistory.class: org.quartz.plugins.history.LoggingJobHistoryPlugin
#org.quartz.plugin.jobInitializer.class: org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin
#org.quartz.plugin.jobInitializer.fileNames: quartz_data.xml
#org.quartz.plugin.jobInitializer.failOnFileNotFound: true
#org.quartz.plugin.jobInitializer.scanInterval: 120
#org.quartz.plugin.jobInitializer.wrapInUserTransaction: false
使用集群模式的配置
org.quartz.scheduler.instanceId: AUTO
org.quartz.jobStore.clusterCheckinInterval=20000
org.quartz.jobStore.isClustered: true
1.3.5重写QuartzJobBean类
public class QuartJobClassBean extends QuartzJobBean{
protected final Log logger = LogFactory.getLog(getClass());
private String targetObject;
private String targetMethod;
private ApplicationContext ctx;
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
try {
logger.info("execute [" + targetObject + "] at once>>>>>>");
Object otargetObject = ctx.getBean(targetObject);
Method m = null;
try {
m = otargetObject.getClass().getMethod(targetMethod, new Class[] {});
m.invoke(otargetObject, new Object[] {});
} catch (SecurityException e) {
logger.error(e.getMessage());
} catch (NoSuchMethodException e) {
logger.error(e.getMessage());
}
} 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;
}
}
1.3.6编写任务类
public class TestQuartJobClass {
public void printjob(){
System.out.println("定时任务0:"+new Date());
}
public void print(){
System.out.println("定时任务1"+new Date());
}
}
1.3.7集群部署
模拟分布式部署
1.3.8启动测试
由以上两个图可以看出,任务调度只在一个服务器上运行了,保证了任务的不重复执行,现在假如我做一件事情就是停掉tomcaT的服务器。quartz框架将自动帮我们把任务切换到另一个服务器上执行
如上图所示tomcat停掉以后,任务自动切换到了另一个上,并且可以看出在15-50之间,在故障切换的过程中有6次定时任务没有跑,所以切换以后备用主机将会自动补跑故障以前的数据。