Tomcat下的定时任务

步骤:

一、实现javax.servlet.ServletContextListener接口

package com.wwm.tomacttimer;

import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class TimerDemo implements ServletContextListener
{
    private Timer timer = null;
	//在服务器关闭的时候执行
	public void contextDestroyed(ServletContextEvent event)
	{
	    if (timer != null) 
	    {
            timer.cancel();
            event.getServletContext().log("定时器已销毁");
        } 
	}
	//在服务器启动的时候执行
	public void contextInitialized(ServletContextEvent event) 
	{
		timer = new Timer(true);  //在这里初始化监听器,在tomcat启动的时候监听器启动,可以在这里实现定时器功能 
		event.getServletContext().log("定时器已启动"); 
		timer.schedule(new myTask(),2000,(5*1000));
		event.getServletContext().log("任务已经添加!");  
	}
}
二、实现执行任务类

package com.wwm.tomacttimer;

import java.util.TimerTask;

public class myTask extends TimerTask 
{
    private static boolean isRunning = false;

    @Override
    public void run() 
    {
        if (!isRunning) 
        {
            isRunning = true;
            //执行任务
            System.out.println("---"+System.currentTimeMillis());
            
            isRunning = false;
//           System.out.println("本次任务结束");
        } 
        else
        {
        	System.out.println("上次任务还在执行");
        }
    }
}
三、然后在web.xml中配置listner
 
  
     com.wwm.tomacttimer.TimerDemo
  


你可能感兴趣的:(Java基础知识总结)