·您的位置: 首页 » 资源教程 » 编程开发 » JAVA、JSP » JAVA-如何实现TIMER功能

JAVA-如何实现TIMER功能

类别: JAVA教程  评论数:0 总得分:0
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




-= 资 源 教 程 =-
文 章 搜 索
关键词:
类型:
范围:
纯粹空间 softpure.com
Copyright © 2006-2008 暖阳制作 版权所有
QQ: 15242663 (拒绝闲聊)  Email: faisun@sina.com
 纯粹空间 - 韩国酷站|酷站欣赏|教程大全|资源下载|免费博客|美女壁纸|设计素材|技术论坛   Valid XHTML 1.0 Transitional
百度搜索 谷歌搜索 Alexa搜索 | 粤ICP备19116064号-1