spring实现定时器
1.新建一个java类,命名为TaskquartzController.class,创建一个方法,名为deleteOrder。注意配置文件中的几个id
public class TaskquartzController { /** * 定时器 * * @see * @since 1.0 */ public void deleteOrder(){ System.out.println("定时器测试"); } }
2.新建一个xml文件,命名为interf-task.xml
里面的内容为
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 实例化bean --> <bean id= "deleteOrderQuartz" class ="com.zhinianblog.taskquartz.controller.TaskquartzController"/> <!-- 配置MethodInvokingJobDetailFactoryBean --> <bean id= "deleteOrderMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="deleteOrderQuartz"/> <property name="targetMethod" value="deleteOrder"/> <property name="concurrent" value="false"/> </bean> <!-- 配置定时表达式 --> <bean id= "deleteOrderTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean" > <property name="jobDetail" ref="deleteOrderMethod" /> <!-- 每5秒执行一次 --> <!-- /代表每隔 --> <!-- 秒 分 时 天 月 ? 年 --> <property name="cronExpression" value="0/5 * * * * ?" /> </bean> <!-- 配置调度工厂 --> <bean id= "testSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers" > <list> <ref bean="deleteOrderTrigger" /> </list> </property> </bean> </beans>
3.在ApplicationContext.xml文件中引入该定时器文件
<!-- 配置定时任务 --> <import resource="interf-task.xml"/>
4.启动项目,就会看到控制台每5秒输出信息