Java Timer的容易应用
Java Timer的简单应用
此定时器主要是通过一个计数器来实现定时功能,使用计数器主要是因为Java提供的Timer中好象没有重新计时的功能。所以只能使用这种自欺欺人的方法了。如果大家有什么更好发使用Timer的方法,欢迎贴出来大家探讨一下。
最近由于工作关系,要使用Java中的Timer,从网上的评论得知这个东东并不是很好用,由于需求也不是太苛刻,所以把它改改就OK了。需求是这样的:
- .在请求到来时开始计时。
- 在请求超过规定时间时,结束计时。
- 在得到页面确认时,重置时间,重新开始计时。
需求很简单,下面是我的定时器实现:
java 代码
- package com.youcompany.yourproject.comet;
- import java.util.Date;
- import java.util.Timer;
- import java.util.TimerTask;
- import com.youcompany.yourproject.core.common.Constants;
- import com.youcompany.yourproject.core.common.DFPropertyOwner;
- import com.youcompany.yourproject.core.error.ParameterException;
- import com.youcompany.yourproject.service.JkControlService;
- public class CometTimer
- {
- private final Timer timer = new Timer();
- private TaskTime myTime = new TaskTime(0,DFPropertyOwner.getKeyNumber("userstate"));
- public CometTimer()
- {
- }
- public void start(ServerThread thread)
- {
- myTime.setService(thread);
- timer.schedule(myTime,new Date(),Constants.STOPFORQUERY * 1000);
- }
- public void restart()
- {
- myTime.restart();
- }
- private class TaskTime extends TimerTask
- {
- private ServerThread service;
- private int counter = 0;//当前技术值
- private int all = 0;//计数最大值
- private boolean isResc = false;//升序还是降,默认升序。
- @Override
- public void run()
- {
- // TODO Auto-generated method stub
- // System.out.println("fdsafdsafdsafdsafdsafdsaf");
- if(this.isResc)
- {
- if((counter--)== 0)
- {
- doWork();
- }
- }
- else
- {
- if((this.counter++)== (this.all - 1))
- {
- doWork();
- }
- }
- }
- public void doWork()
- {
- System.out.println("User is out of time!!");
- if(this.service == null)
- {
- throw new ParameterException("name");
- }
- else
- {
- JkControlService.leave(service);
- }
- timer.cancel();
- }
- public TaskTime(int i , int j)
- {
- // TODO Auto-generated method stub
- this.setAll(j);
- this.setCounter(i);
- }
- /**
- * 设置初始值
- * @param i: 初始值
- * @param j: 技数个数
- */
- public TaskTime(int i , int j,boolean isRESC)
- {
- // TODO Auto-generated method stub
- this.setAll(j);
- this.setCounter(i);
- this.setResc(isRESC);
- }
- public void setCounter(int counter)
- {
- if(counter > 0)
- this.counter = counter;
- }
- public void setAll(int all)
- {
- if(all >this.counter)
- this.all = all;
- }
- public boolean isResc()
- {
- return isResc;
- }
- public void restart()
- {
- if(this.isResc)
- {
- this.counter = this.all;
- }
- else
- {
- this.counter = 0;
- }
- }
- /**
- * 是否是递减记数。
- * @param isResc
- */
- public void setResc(boolean isResc)
- {
- this.isResc = isResc;
- }
- public void setService(ServerThread service)
- {
- this.service = service;
- }
- }
- }
1 楼
Jatula
2008-09-16
以前用过一次,但是感觉,做些没用的工作,他真的不错,像打印一句话之类的,很灵,但在里面再个方法处理,马上挂掉;也挺郁闷的;