java定时器的实现方式:
1)java.util.Timer.
2)ServletContextListener.
3)org.springframework.scheduling.timer.ScheduledTimerTask
第一种:
Timer timer=new Timer();
timer.schedule(new ListByDayTimerTask(),10000,86400000);
其中ListByDayTimerTask类必须extends TimerTask里面的run()方法。
第二种
实现 ServletContextListener 接口
这需要在web容器环境中,在web server启动后就可以
真正的实现也是通过timer的,因为需要在
contextInitialized方法中加入启动Timer的代码,在contextDestroyed
方法中加入cancel该Timer的代码;然后在web.xml中,加入listener:
<listener>
<listener-class>**</listener-class>
</listener>
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TimerTest implements ServletContextListener{
private Timer timer = null;
public void contextDestroyed(ServletContextEvent event) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
public void contextInitialized(ServletContextEvent event) {
//tomcat启动的时候监听器启动,定时器功能代码执行
timer = new Timer(true);
event.getServletContext().log("定时器已启动");//添加日志,可在tomcat日志中查看到
timer.schedule(new TaskUnit(event.getServletContext()),0,60*1000);//调用 TaskUnit ,0表示任务无延迟,60*1000表示每隔1分钟执行任务,}
}
import java.util.Calendar;
import java.util.TimerTask;
import javax.servlet.ServletContext;
public class TaskUnit extends TimerTask
{
private static final int C_SCHEDULE_HOUR = 0;
private static boolean isRunning = false;
private ServletContext context = null;
public TaskUnit(ServletContext context)
{
this.context = context;
}
@Override
public void run()
{
Calendar c = Calendar.getInstance();
if(!isRunning)
{
if(C_SCHEDULE_HOUR == c.get(Calendar.HOUR_OF_DAY))
{
isRunning = true;
context.log("开始执行指定任务");
isRunning = false;
context.log("指定任务执行结束");
}
else
{
context.log("上一次任务执行还未结束");
}
}
}
}
第三种org.springframework.scheduling.timer.ScheduledTimerTask
不通过Timer类了,而是通过spring的方式
在schedulingContext-timer.xml中加入下面的内容就:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="timer" class="org.springframework.scheduling.timer.TimerFactoryBean">
<property name="scheduledTimerTasks">
<list>
<ref local="springTask"/>
</list>
</property>
</bean>
<bean id="bussinessTask" class="*******"/>
<bean id="springTask" class="org.springframework.scheduling.timer.ScheduledTimerTask">
<property name="timerTask">
<ref bean="bussinessTask"/>
</property>
<property name="delay">
<value>1000</value>
</property>
<property name="period">
<value>3*60*1000</value>
</property>
</bean>
</beans>