web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<!-- servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet-->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- 要调度的对象 -->
<bean id="testQuarz" class="springTimer.TestQuarz"></bean>
<!-- 要调度的对象结束 -->
<!--定义定时执行testQuarz 这个bean中的sayHelloWorld()方法 这个任务-->
<bean id="sayHelloWorldTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="testQuarz" />
</property>
<property name="targetMethod">
<value>sayHelloWorld</value>
</property>
</bean>
<!-- 结束 -->
<!--触发器的bean的设置,在这里我们设置了我们要触发的jobDetail是哪个。
这里我们定义了要触发的jobDetail是helloworldTask,即触发器去触发哪个bean..
并且我们还定义了触发的时间:每天23:00-23:59之间pm-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="sayHelloWorldTask" />
</property>
<property name="cronExpression">
<!-- 关键在配置此表达式 -->
<value>0 * 23 * * ?</value>
</property>
</bean>
<!--管理触发器的总设置,管理我们的触发器列表,可以在bean的list中放置多个触发器。-->
<bean autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="cronTrigger" />
</list>
</property>
</bean>
</beans>
被调度的类:
package springTimer;
import java.util.Date;
/**
*
* @author 朱湘鄂
* @date 2011-04-25
* 说明:被调度的类
*
*/
public class TestQuarz {
public void sayHelloWorld(){
System.out.println("现在时间是"+new Date().getHours());
System.out.println("现在时间是"+new Date().getMinutes());
}
}
控制台结果每分钟一次:
现在时间是23
现在时间是10
现在时间是23
现在时间是11
现在时间是23
现在时间是12
现在时间是23
现在时间是13
现在时间是23
现在时间是14