java手写的定时器.
此为转载.
用JAVA写了一个定时器类,此类作为一个线程运行,包含了一个队列存放定时器消息,通过比较定时器的触发时间,俺触发事件先后顺序排列队列。
import java.util.concurrent.*;
import java.util.*;
public class TimerTask implements Runnable {
/**定时器事件队列*/
PriorityBlockingQueue<TimerSlot> queue_ = new PriorityBlockingQueue<TimerSlot>(2048);
/** Creates a new instance of TimerTask */
public TimerTask() {
}
/**设置定时器,并放入队列*/
public synchronized Object setTimer(String taskname, String eventname, int timerevent, int delay, Object param){
TimerSlot slot = new TimerSlot();
slot.taskname = taskname;
slot.eventname = eventname;
slot.timerevent = timerevent;
slot.expiretime = System.currentTimeMillis() + delay;
slot.param = param;
try {
queue_.put(slot);
} catch (Exception ex) {
}
return 0;
}
/**去掉指定的定时器*/
protected synchronized int killTimer(Object timer){
if (queue_.remove(timer)){
return 0;
}
return -1;
}
/**关闭操作*/
public void close(){
queue_.clear();
}
/**线程运行,检查定时器是否触发*/
public void run(){
while (true){
try{
TimerSlot slot = queue_.peek();
if (slot == null) {
Thread.sleep(50);
continue;
}
long now = System.currentTimeMillis();
if (now < slot.expiretime) {
Thread.sleep(Math.min(slot.expiretime-now,50));
continue;
}
queue_.remove();
TaskMsg taskmsg = new TaskMsg();
taskmsg.eventName=slot.eventname;
taskmsg.eventNo = slot.timerevent;
taskmsg.msg = (slot.param);
taskmsg.sender = "__timer";
taskmsg.receiver = slot.taskname;
TaskFactory.getInstance().getTaskByName(slot.taskname).
putmsgtoqueue(taskmsg);
}catch(InterruptedException e){
return;
}
}
}
class TimerSlot implements java.lang.Comparable<TimerSlot>{
public String eventname;
public String taskname;
public int timerevent;
public long expiretime; // ms, System.current+delay
public Object param;
public int compareTo(TimerSlot other) {
return (int)(this.expiretime-other.expiretime);
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。