转载于:http://blog.csdn.net/softwave/article/details/6958180
定时器GoogleListener类:
- package cn.edu.KFC.bean;
- import java.util.Timer;//定时器类
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
- import cn.edu.KFC.bean.GoogleTimer;
- public class GoogleListener implements ServletContextListener {
- private Timer timer = null;
- public void contextInitialized(ServletContextEvent event) {
- // 在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能
- timer = new Timer(true);
- // 添加日志,可在tomcat日志中查看到
- event.getServletContext().log("定时器已启动");
- System.out.println("定时器已启动");
- // 调用GoogleTimer,0表示任务无延迟,5*1000表示每隔5秒执行任务,60*60*1000表示一个小时,24*60*60*1000表示一天。
- timer.schedule(new GoogleTimer(event.getServletContext()), 0, 2 * 60 * 1000); //每2分钟执行一次GoogleTimer类
- event.getServletContext().log("已经添加任务");
- System.out.println("定时器已添加");
- }
- public void contextDestroyed(ServletContextEvent event) {// 在这里关闭监听器,所以在这里销毁定时器。
- timer.cancel();
- event.getServletContext().log("定时器销毁");
- }
- }
被调用的GoogleTimer类的写法,注意extends TimerTask,并且在run()方法中执行业务:
- package cn.edu.KFC.bean;
- import java.util.Calendar;
- import java.util.TimerTask;
- import javax.servlet.ServletContext;
- import cn.edu.KFC.bean.GoogleAnalytics;
- public class GoogleTimer extends TimerTask{
- private ServletContext context = null;
- GoogleAnalytics ga = new GoogleAnalytics();
- public GoogleTimer(ServletContext context){
- this.context = context;
- }
- public void run(){
- ga.myTest();
- }
- }
最后,在web.xml中设置监听器
- <listener>
- <listener-class>cn.edu.KFC.bean.GoogleListener</listener-class>
- </listener>