1、前言:之前写了一个最简单的quartz案例,那个只是最基础的Quartz运用,很有幸,Spring已经将Quartz集成进去,所以我们只需配置几个简单的步骤就可以进行静态定时器的管理。
2、首先初始化一个任务Job,也就是具体要做的业务。
- package com.telek.quartz;
- import java.util.Date;
- /**
- * Description:具体业务代码
- * HelloWorld.java Create on 2012-11-23 上午9:30:50
- * @author 张景
- * @version 1.0
- * Copyright (c) 2012 telek. All Rights Reserved.
- */
- public class HelloWorld {
- public void sayHello() {
- System.out.println("Hello World : " + new Date());
- }
- }
3、配置applicationContext-quartz.xml文件,将具体任务与触发器及其部署到调度器上的信息分别配置到spring的bean中。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
- <beans>
- <bean id="helloWorld" class="com.telek.quartz.HelloWorld"></bean>
- <!-- 实例化一个具体任务 -->
- <bean id="helloWorldJobDetail"
- class="com.telek.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean ">
- <property name="targetObject" ref="helloWorld" />
- <property name="targetMethod" value="sayHello" />
- </bean>
- <!-- 为这个任务添加触发器 -->
- <bean id="helloWorldTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
- <property name="jobDetail" ref="helloWorldJobDetail" />
- <property name="cronExpression" value="0/6 * * * * ?" />
- </bean>
- <!-- 将具体任务和触发器部署到调度器scheduler上 -->
- <bean name="quartzScheduler"
- class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
- <property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
- <property name="triggers">
- <list>
- <!-- 此处可添加多个触发器 -->
- <ref bean="helloWorldTrigger" />
- </list>
- </property>
- </bean>
- </beans>
4、在web.xml配置文件中加载上面的spring配置文件。
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- version="3.0">
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- /WEB-INF/classes/applicationContext-quartz.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- </web-app>
5、将web部署到tomcat服务器(其他服务器也行)。
6、观察结果:在控制台上在每分钟6秒的倍数会打印出helloWorld和当前时间。