Spring定时器TimerTask用法:
在tomcat服务启动,spring定时器容器加载时会执行定时器里的任务,可设置时间间隔和延迟执行时间,具体做法如下:
spring.xml 中的配置
<!-- 工具类 -->
<bean id="timerJob" class="timer.TimerJob"></bean>
<bean id="scheduledTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="timerJob" />
</property>
<!--任务执行周期 5s (此处单位是毫秒) -->
<property name="period">
<value>5000</value>
</property>
<!--延时10s 执行任务 -->
<property name="delay">
<value>10000</value>
</property>
</bean>
<!--启动定时器 -->
<bean id="timerBean" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref bean="scheduledTask" />
</list>
</property>
</bean>
定时任务类
/**
* 当启动服务后加载完定时器,延迟10秒后,每隔5秒执行一次run()
**/
package timer;
import java.util.TimerTask;
//继承了TimerTask这个类
public class TimerJob extends TimerTask {
@Override
public void run() {
system.out.print("此处是你需要的定时操作");
}
}
注意:timer的缺点是对于指定了具体的年月日时分秒而执行的任务还是不能解决。
转载于:https://blog.51cto.com/leoxia/1729950