1、实现监听启动的接口
package cn.geekapp.timer;
import java.util.Timer;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener{
/**
* 定时器
*/
private static Timer mTimer = null;
/**
* 定时器启动间隔
*/
private static final long mPeriod = 1 * 10 * 1000L;//10秒
@Override
public void contextDestroyed(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("contextDestroyed begin");
if(mTimer != null){
mTimer.cancel();
}
System.out.println("contextDestroyed end");
}
@Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
System.out.println("contextInitialized begin");
mTimer = new Timer(true);
mTimer.scheduleAtFixedRate(new MyTimerTask(), mPeriod, mPeriod);
System.out.println("contextInitialized end");
}
}
2、定义TimerTask
package cn.geekapp.timer;
import java.util.TimerTask;
public class MyTimerTask extends TimerTask{
private static boolean isRun = false;
@Override
public void run() {
// TODO Auto-generated method stub
try {
if(isRun){
System.out.println("task is running,return!");
return;
}
isRun = true;
System.out.println("MyTimerTask run at time "+System.currentTimeMillis());
//业务逻辑代码
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
isRun = false;
}
}
}
3、web.xml添加监听
cn.geekapp.timer.MyListener
原创内容转载请保留出处GEEK笔记(https://www.geekapp.cn/)。