Javaweb中的定时器
2021-02-16 15:22
标签:timertask cal cancel code pip end listen mon XML 1.任务类 2.监听类 3.在web.xml中配置 Javaweb中的定时器 标签:timertask cal cancel code pip end listen mon XML 原文地址:https://www.cnblogs.com/dch0/p/12706608.htmlimport java.util.TimerTask;
import javax.servlet.ServletContext;
public class MyTask extends TimerTask{
private ServletContext context = null;
public CleanTpIpTask(ServletContext servletContext) {
this.context = servletContext;
}
@Override
public void run() {
//定时任务逻辑代码
}
}
import java.util.Calendar;
import java.util.Date;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyTaskListener implements ServletContextListener {
private java.util.Timer timer = null;
MyTask myTask = null;
public void contextDestroyed(ServletContextEvent arg0) {
timer.cancel();
}
public void contextInitialized(ServletContextEvent arg0) {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
c.set(year, month, day, 3, 0, 0);//项目启动当天凌晨3点执行1次,如果已经超过凌晨3点,立刻执行
Date date = c.getTime();
timer = new java.util.Timer(true);
int period = 24 * 60 * 60 * 1000;//执行间隔
if(myTask==null){
myTask = new MyTask(arg0.getServletContext());
timer.schedule(new MyTask(arg0.getServletContext()), date, period);
//timer.schedule(new CleanTpIpTask(arg0.getServletContext()), date);//只执行1次
//timer.schedule(new CleanTpIpTask(arg0.getServletContext()), 0, period);//项目启动立刻执行,每隔period 毫秒执行1次
}
}
}
listener>
listener-class>webservice.MyTaskListenerlistener-class>
listener>