延遲隊列DelayQueue

應用場景:有一批廣告須要不定時上下架,有可能上下架的時間間隔很長,就不必用定時器輪詢,用延遲隊列進行任務執行。java

public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        DelayQueue<Message> delayQueue =  new DelayQueue<>();
        for (int i=1;i<11;i++){
            Message m = new Message(i+"",System.currentTimeMillis()+i*1000);
            delayQueue.add(m);
        }

        while(!delayQueue.isEmpty()){
            Message message = delayQueue.take();//此處會阻塞
            //執行廣告上下架操做
        }

    }
}

class Message  implements  Delayed{
    private String id;
    private long insertTime ;//開始時間,廣告上下架時間。

    public Message(String id,long insertTime){
        this.id = id;
        this.insertTime =  insertTime;
    }

    //獲取失效時間
    @Override
    public long getDelay(TimeUnit unit) {
        //獲取失效時間
        return this.insertTime+60000-System.currentTimeMillis();
    }


    @Override
    public int compareTo(Delayed o) {
        //比較 1是放入隊尾  -1是放入隊頭
        Message that = (Message)o;
        if(this.insertTime>that.insertTime){
            return 1;
        }
        else  if(this.insertTime==that.insertTime){
            return 0;
        }else {
            return -1;
        }
    }

    public String getId() {
        return id;
    }
}
相關文章
相關標籤/搜索