1 code
package util;
import org.apache.log4j.*;
public class TaskJob {
public static Logger log = Logger
.getLogger(TaskJob.class);
public void SayHello() {
// TODO Auto-generated method stub
try {
log.info("处理任务开始>........");
// 业务逻辑代码调用
System.out.println("时间[" + new java.util.Date().toLocaleString()
+ "]----->大家好啊!");
log.info("处理任务结束!");
} catch (Exception e) {
log.error("处理任务出现异常", e);
}
}
}
2.接下来的在spring 里配置:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean name="taskJob" class="util.TaskJob" />
<bean id="methodInvokingJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref bean="taskJob" />
</property>
<property name="targetMethod">
<value>SayHello</value>
</property>
</bean>
<!-- 配置触发器 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<!-- 这里不可以直接在属性jobDetail中引用taskJob,因为他要求的是一个jobDetail类型的对象,所以我们得通过MethodInvokingJobDetailFactoryBean来转一下 -->
<property name="jobDetail">
<ref bean="methodInvokingJobDetail" />
</property>
<!-- 每天的8点到21点每隔1分钟触发,具体说明见附录 -->
<property name="cronExpression">
<value>0 * 08-21 * * ?</value>
</property>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref local="cronTrigger" />
</list>
</property>
</bean>
</beans>
3.测试执行的类,只要把spring的配置文件加载了就可以看到定时任务运行了。
package util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("加载spring配置文件....");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("加载配置文件完毕!");
// ApplicationContext context2 = new ClassPathXmlApplicationContext("test/timerTask/quartzTimer.xml");
}
}
如果要在web项目中运行的话还要在web.xml 中加入如下代码:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>