WEB开发网
开发学院WEB开发Jsp JAVA-如何实现TIMER功能 阅读

JAVA-如何实现TIMER功能

 2008-01-05 09:06:48 来源:WEB开发网   
核心提示:java-如何实现TIMER功能 2004-11-8Author :Meanson WangEmail:meansonw@hotmail.comDate:2004-11-8JAVA-如何实现TIMER功能1.listener classpackage timer;import java.util.TimerTask;i

  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

Tags:JAVA 如何 实现

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接