打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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);
        }
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【redis】使用redis RedisAtomicLong生成自增的ID值
如何利用.net Application做缓存处理
spring boot下JedisCluster方式连接Redis集群的配置
经典:Redis分布式锁的正确实现方式
.net core使用jwt自动续期
几行代码,搞定 SpringBoot 接口恶意刷新和暴力请求!
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服