package com.ripsoft.util; import java.util.Calendar;
import java.util.Timer; import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class TimerListener implements ServletContextListener{
private Timer timer = null; @Override
public void contextInitialized(ServletContextEvent event) {
timer = new Timer(true);
event.getServletContext().log("定时器已启动"); //设置执行时间
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
//定制每天的11:00:00执行
calendar.set(year, month, day, 11, 00, 00);
java.util.Date date = calendar.getTime();
int period = 30 * 1000;
//每天的date时刻执行TestTask,每隔30秒重复执行
timer.schedule(new TestTask(), date, period);
//每天的date时刻执行TestTask, 仅执行一次
//timer.schedule(new TestTask(), date);
} @Override
public void contextDestroyed(ServletContextEvent event) {
if (timer != null) {
timer.cancel();
event.getServletContext().log("定时器销毁");
}
}
}
package com.ripsoft.util; import java.util.TimerTask; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; public class TestTask extends TimerTask{
protected final Log logger = LogFactory.getLog(getClass()); private static boolean isRunning = false; @Override
public void run() {
if (!isRunning) {
isRunning = true;
logger.info("开始执行任务。"); int i = 0;
while (i++ < 10) {
logger.info("已完成任务的" + i + "/" + 10);
} isRunning = false;
logger.info("任务执行结束。"); } else {
logger.info("上一次任务执行还未结束,本次任务不能执行。");
} }
}
1.TestTimerListener.java执行定时任务,实现servlet的ServletContextListener接口,当服务器启动时开始执行TestTask任务
2.想要任务在服务器启动时定时执行,就要借助监听实现需要在web.xml中做如下配置
<listener>
<listener-class>com.ripsoft.util.TimerListener</listener-class>
</listener>