Delay延迟队列

Posted yifansj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Delay延迟队列相关的知识,希望对你有一定的参考价值。

DelayEvent.java

public class DelayEvent2 implements Delayed {
    //到期时间
    private Date startDate;

    public DelayEvent2(Date startDate) {
        this.startDate = startDate;
    }

    public int compareTo(Delayed o){
        long result = this.getDelay(TimeUnit.NANOSECONDS)  - o.getDelay(TimeUnit.NANOSECONDS);
        if (result < 0) {
            return -1;
        } else if (result > 0) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * 返回与此对象相关的剩余延迟时间,以给定的时间单位表示
     */
    public long getDelay(TimeUnit unit){
        Date now = new Date();
        long diff = startDate.getTime() - now.getTime();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }
}

DelayTask.java

/**
 * 任务任务
 * 作用:添加100个新DelayEvent到DelayQueue队列中
 */
public class DelayTask2 implements Runnable{
    //添加时间
    private int id;
    //队列
    private DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>();

    public DelayTask2(int id, DelayQueue<DelayEvent2> dq) {
        this.id = id;
        this.dq = dq;
    }

    public void run() {
        //旧Date
        Date date = new Date();
        //新Date
        Date delay = new Date();
        delay.setTime(date.getTime() + id * 1000);

        System.out.println("Thread 时间+:" + id + " 新Date:" + delay);

        //将100个DelayEvent放入DelayQueue
        for(int i = 0;i < 100;i++){
            DelayEvent2 de = new DelayEvent2(delay);
            dq.add(de);
        }
    }
}

DelayDequeueMain.java

public class DelayDequeMain2 {
    public static void main(String[] args) throws Exception{
        DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>();
        Thread threads[] = new Thread[5];
        for(int i = 0;i < threads.length;i++){
            DelayTask2 task = new DelayTask2(i+1,dq);
            threads[i] = new Thread(task);
        }
        for(int i = 0;i < threads.length;i++){
            threads[i].start();
        }
        for(int i = 0;i < threads.length;i++){
            threads[i].join();
        }
        do{
            int counter = 0;
            DelayEvent2 delayEvent2;
            do{
                delayEvent2 = dq.poll();
                if(delayEvent2 != null){
                    counter++;
                }
            }while(delayEvent2!=null);
            System.out.println("At " + new Date() + " you have read " + counter + " event");
            TimeUnit.MILLISECONDS.sleep(500);
        }while(dq.size()>0);
    }
}

 

以上是关于Delay延迟队列的主要内容,如果未能解决你的问题,请参考以下文章

rocketmq实现延迟队列精确到秒级实现方案2-时间轮和delay-file实现

delay()延迟

[ jquery 效果 delay(duration,[queueName]) ] 此方法用于对队列中的下一项的执行设置延迟

# Java 常用代码片段

# Java 常用代码片段

Spring Boot 实现 RabbitMQ 延迟消费和延迟重试队列