延迟队列DelayQueue

本文介绍了如何在Java中使用Slf4j日志框架配合DelayQueue实现一个简单的定时任务队列,通过`DelayedTask`类封装任务并设置到期时间,`DelayQueue`用于按到期顺序执行任务。
摘要由CSDN通过智能技术生成

示例代码

@Slf4j
public class DelayQueueTest {

    public static  class DelayedTask implements Delayed {

        /**
         * 消息体
         * */
        private Object data;

        /**
         * 到期时间,毫秒
         * */
        private Long deadline;

        public DelayedTask(Object data, int expireSeconds){
            this.data = data;
            this.deadline = System.currentTimeMillis() + expireSeconds * 1000;
        }

        /**
         * 获取元素的剩余的有效期
         * */
        @Override
        public long getDelay(TimeUnit unit) {
            long remain = deadline - System.currentTimeMillis();
            if(remain <= 0){
                remain = 0;
            }
            return unit.convert(remain, TimeUnit.MILLISECONDS);
        }

        /**
         * 比较元素的剩余,看谁先到期
         * */
        @Override
        public int compareTo(Delayed o) {
            long result = this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS);
            if(result > 0){
                return 1;
            }else if(result < 0){
                return -1;
            }else{
                return 0;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueue<DelayedTask> delayQueue = new DelayQueue<>();
        DelayedTask task1 = new DelayedTask("data 5 second", 5);
        DelayedTask task2 = new DelayedTask("data 3 second", 3);
        DelayedTask task3 = new DelayedTask("data 1 second", 1);
        // 向延迟队列放任务
        delayQueue.put(task1);
        delayQueue.put(task2);
        delayQueue.put(task3);
        log.info("消息发送完成");
        // 如果队列中没有到期的元素,take会阻塞等待
        while(true){
            DelayedTask task = delayQueue.take();
            log.info("获取延迟任务:task:{}", task.data);
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值