⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timertask.java

📁 java定时器
💻 JAVA
字号:
import java.util.concurrent.PriorityBlockingQueue;

public class TimerTask implements Runnable{
    /** *//**定时器事件队列*/
	PriorityBlockingQueue<TimerSlot> queue_=new PriorityBlockingQueue<TimerSlot>(2048);
    
    
    /** *//**设置定时器,并放入队列*/
    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;
        public Object param;
        public int compareTo(TimerSlot  other){
            return (int)(this.expiretime-other.expiretime);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -