2007-12-10
Java Timer的简单应用
关键字: java 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;
- }
- }
- }
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 4714 次
- 性别:

- 来自: 烟台

- 详细资料
搜索本博客
最新评论
-
Ext 验证
tubinee 写道支持!!! 一个提议: 考虑做个可以从server端验证的 ...
-- by techno_it -
Ext 验证
支持!!! 一个提议: 考虑做个可以从server端验证的vtype、
-- by tubinee -
使用传统IO包编写的Servle ...
drbeckham 写道 JDK6.0好像在Linux下支持EPOLL,性能应该 ...
-- by skydream -
使用传统IO包编写的Servle ...
用MINA吧,效率很好,也支持线程池,我自己测试过在普通配置(C2.6, 512 ...
-- by drbeckham -
使用传统IO包编写的Servle ...
如果并发不高的话,可以用我方法
-- by ssuupv






评论排行榜