1.创建类实现接口 ServletContextListener
2.实现方法contextInitialized(初始化)和contextDestroyed(销毁)
package com.baosight.webapp.util;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SaveFile implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("+++++++++++++++++++Game Over");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
Runnable runnable = new Runnable() {
public void run() {
// task to run goes here
System.out.println("============time:"+new Date());
System.out.println("Hello !!");
}
};
ScheduledExecutorService service = Executors
.newSingleThreadScheduledExecutor();
System.out.println(new Date());
//第一个参数是触发事件s,第二个参数是执行延迟时间s,第三个参数是时间间隔
service.scheduleAtFixedRate(runnable, 1, 10, TimeUnit.SECONDS);
}
public static void main(String[] args) {
Date date=new Date();
//下周一0点据当前时间的秒数
int interval = (7 - date.getDay() + 1)*24*3600 - date.getHours()*3600 - date.getMinutes()*60 - date.getSeconds();
}
}
3.web.xml文件监听类
<listener>
<listener-class>com.baosight.webapp.util.SaveFile</listener-class>
</listener>