web中TImer定时器的使用(web.xml)

1操作类

package com;

import java.util.TimerTask;

public class JinTask extends TimerTask {

public void run() {
//可以定义自己要处理的方法
System.out.println("开始执行了!!!!");
System.out.println(System.currentTimeMillis());

}

}
2定时器监听类

package com;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Timer;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class JinListener implements ServletContextListener {
//Fields
private Log logger = LogFactory.getLog(this.getClass()); //日志
private static Timer timer;
private static DeleteImageTask task = new JinTask();


public void contextDestroyed(ServletContextEvent arg0) {
logger.debug("调用contextDestroyed方法");
if (timer != null) {
timer.cancel();
logger.debug("Timer Canceled");
}
//timer.schedule(task, 0, 100);
logger.debug("contextDestroyed方法执行完成");

}


public void contextInitialized(ServletContextEvent arg0) {
logger.debug("调用contextInitialized方法");
try {

timer = new Timer(true);
GregorianCalendar now = new GregorianCalendar();
//每天9:22执行 Calendar.DAY_OF_YEAR(一年中第一天的值为 1)
//HOUR_OF_DAY( 用于 24 小时制时钟)
//WEEK_OF_YEAR(第一个星期为1)
now.set(Calendar.HOUR_OF_DAY, 9);
now.set(Calendar.MINUTE, 22);
now.set(Calendar.SECOND, 0);
timer.schedule(task, now.getTime());

} catch (Exception e) {
e.printStackTrace();
logger.error("Unable to initialize Schedule.");
}
logger.debug("contextInitialized方法执行完成");

}
}

3web.xml中的配置

<listener>
<listener-class>
com.JinListener
</listener-class>
</listener>

你可能感兴趣的:(apache,Web,xml,servlet)