quartz是一个定时任务组件,非常方便好用
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!--调度工厂-->
<!-- 定时任务 -->
<bean id="startQuartz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="mytrigger"></ref>
</list>
</property>
</bean>
<!-- 使用MethodInvokingJobDetailFactoryBean,任务类可以不实现Job接口,通过targetMethod指定调用方法-->
<bean id="myjobdetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="TestService" />
<property name="targetMethod" value="print" />
</bean>
<!--调度触发器-->
<bean id="mytrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="myjobdetail" />
<property name="cronExpression" value="0 0/1 * * * ?" />
</bean>
<bean id="TestService" class="wangcc.service.impl.TestServiceImpl"></bean>
</beans>
测试代码
package wangcc.test;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestQuartz {
public static void main(String[] args) {
System.out.println( " Test start. " );
ApplicationContext context= new ClassPathXmlApplicationContext("applicationContext-quartz.xml");
// 如果配置文件中将startQuertz bean的lazy-init设置为false 则不用实例化
System.out.print( " Test end..\n " );
}
}
package wangcc.service.impl;
import java.util.Date;
import wangcc.service.TestService;
public class TestServiceImpl implements TestService{
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("时间为:"+new Date().toString());
}
}