Java-如何实现TIMER功能
2004-11-8
Author :Meanson Wang
Email:meansonw@hotmail.com
Date:2004-11-8
JAVA-如何实现TIMER功能
1.listener class
package timer;
import java.util.TimerTask;
import java.util.Timer;
import javax.servlet.*;
public class RemindListener implements ServletContextListener {
private java.util.Timer timer = null;
public void contextInitialized(ServletContextEvent sce) {
timer = new java.util.Timer(true);
sce.getServletContext().log(new java.util.Date()+"Timer start up!");
timer.schedule(new RemindTask(),0,1*60*1000);//1 minute roll
sce.getServletContext().log(new java.util.Date()+"Schedule loaded!");
}
public void contextDestroyed(ServletContextEvent sce) {
timer.cancel();
sce.getServletContext().log(new java.util.Date()+"Timer destroyed!");
}
}
2.Task class
package timer;
import java.util.TimerTask;
import java.util.Calendar;
public class RemindTask extends TimerTask{
private static final int C_SCHEDULE_HOUR = 15;
private static boolean isRunning = false;
public RemindTask() {
}
public void run() {
Calendar cal = Calendar.getInstance();
if (!isRunning) {
if (C_SCHEDULE_HOUR == cal.get(Calendar.HOUR_OF_DAY)) {
isRunning = true;
System.out.println(new java.util.Date()+"task start");
//TODO for example
int i = 0;
while (i++ < 10) {
System.out.println(new java.util.Date()+"Done!task" + i + "/" + 10);
}
isRunning = false;
System.out.println(new java.util.Date()+"All task Done!");
}
}
else
{
System.out.println(new java.util.Date()+"Task existed!");
}
}
}
3.loadonstart in web.XML
<listener>
<listener-class>timer.RemindListener</listener-class>
</listener>
4.restart server