1.先创建要执行任务的java类
package com.witon.test;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
private String param;
public void run(){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("the param is:"+param+" ! Time is "+ format.format(new Date()));
}
}
2.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
3.spring配置
<?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-3.0.xsd">
<!-- 定义我们要运行的类,可以使用注入,定制一些参数 -->
<bean id="businessTestTime" class="com.witon.test.Test">
<property name="param" value="Spring Timer test"></property>
</bean>
<!-- 每个定义的任务都要在这里引用才能运行 schedule:时刻表、清单、目录 -->
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="businessTestTrigger" />
</list>
</property>
</bean>
<!-- 引用、配置要运行的方法 -->
<bean id="businessTestDetail"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="businessTestTime" />
</property>
<!-- 是否同时发生 -->
<property name="concurrent" value="false"></property>
<!-- 目标方法 -->
<property name="targetMethod" value="run"></property>
</bean>
<!-- 引用、定制时间间隔 -->
<bean id="businessTestTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="businessTestDetail"/>
</property>
<property name="cronExpression">
<value>0/5 * * * * ?</value>
</property>
</bean>
</beans>
4.启动时自动执行任务列表