Spring Timer实现

时间:2021-09-07 20:21:27

定时器:继承java.util.TimerTask类实现run方法

package com.zbb.framework.util.timer;

import java.util.TimerTask;

import com.zbb.business.user.service.IUsOrderService;
/**
*
* @author Vortex
* 继承java.util.TimerTask类实现run方法
* 该类实现spring定时器功能,spring配置文件spring-util.xml
* 该定时器功能实现限制用户在规定时间内支付订单,否则取消支付权限
*/
public class TimerTaskExample extends TimerTask{
private static boolean isrunning = true; private IUsOrderService usOrderService;
@Override
public void run() {
if(!isrunning){
isrunning = true;
/*
* 业务实现区
*/
try {
usOrderService.updateByIds();
} catch (Exception e) {
e.printStackTrace();
}
isrunning = false;
}else{
System.out.println("定时器启动。。。");
isrunning = false;
}
}
public IUsOrderService getUsOrderService() {
return usOrderService;
}
public void setUsOrderService(IUsOrderService usOrderService) {
this.usOrderService = usOrderService;
} }

  spring配置文件:spring-util.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 配置需要运行的类 -->
<bean id="reportTimerTask" class="com.zbb.framework.util.timer.TimerTaskExample">
<property name="usOrderService" ref="usOrderService" />
</bean>
<!-- 配置Spring定时器 -->
<!-- timerTask属性告诉ScheduledTimerTask运行哪个bean, period属性每间隔(30秒)运行一次, delay属性延迟启动(10000毫秒)Spring定时器 -->
<bean id="scheduleReportTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask" ref="reportTimerTask"></property>
<property name="period"><value>30000</value></property>
<property name="delay"><value>0</value></property>
</bean>
<!-- 启动Spring定时器 -->
<bean id="scheduleReportFactory" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list><ref bean="scheduleReportTask" /></list>
</property>
</bean>
</beans>