java实现延时队列

本文介绍了如何使用Java实现一个延时队列,主要用于用户登录后的延迟消息推送。通过实现Delayed接口并结合DelayQueue,创建了一个消息实体类,能够在指定时间后发送通知。文中还展示了如何模拟添加数据到队列,并测试了批量取出的修改效果,讨论了不同比较策略对取出顺序的影响。
摘要由CSDN通过智能技术生成
延时队列主要应用场景是用户登录后延时推送消息,通知等,一般用mq中间件来弄,下面我来用java实现

一、消息实体类实现Delayed接口
import lombok.Data;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 消息实体类实现Delayed接口
 * @author zhanqi
 * @since 2021/5/13 13:46
 */

@Data
public class Message implements Delayed {
    private String body;
    private Long executeTime;

    public Message(String body,Long executeTime, TimeUnit unit){
          this.body=body;
          this.executeTime= System.currentTimeMillis() + (executeTime > 0? unit.toMillis(executeTime): 0);
    }
    @Override
    public long getDelay(TimeUnit unit) {
        return executeTime - System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {
        Message msg = (Message) o;
        long diff = this.executeTime - msg.executeTime;
        //diff>0是一次取出
        if (diff <= 0) {
            return -1;
        } else {
            return 1;
        }
    }
}

 

二、main运行,这里用System.in模拟添加数据

import java.util.Scanner;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author zhanqi
 * @since 2021/5/13 13:47
 */
public class DelayQueueTest {

    public static void main(String[] args) {
        // 创建延时队列
        DelayQueue<Message> queue = new DelayQueue<>();
        new Thread(new Consumer(queue)).start();
        Scanner input = new Scanner(System.in);

        //循环添加System.in
        while (true) {
            String str = input.next();
            if (null != str) {
                Message m = new Message(str, 5l, TimeUnit.SECONDS);
                queue.offer(m);
            }
        }
    }
}

 

三、运行结果,延时效果已经出现

四、我们现在测试延时批量取出修改代码将diff<=0改diff>0

五、效果是一次取出

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
延时队列和定时任务的区别在于,延时队列是按照元素添加的时间来进行排序,而定时任务是按照预定的时间来触发执行的。延时队列可以用于实现某些需要延迟处理的业务场景,例如延迟发布、延迟重试等场景,而定时任务则适用于需要周期性执行任务的场景。 下面是使用Java实现延时队列的示例代码: ``` import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayQueueDemo { public static void main(String[] args) { DelayQueue<DelayedElement> delayQueue = new DelayQueue<>(); delayQueue.offer(new DelayedElement("A", 3000)); delayQueue.offer(new DelayedElement("B", 2000)); delayQueue.offer(new DelayedElement("C", 1000)); while (!delayQueue.isEmpty()) { try { DelayedElement element = delayQueue.take(); System.out.println(element.getData() + "被取出,时间为:" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } } class DelayedElement implements Delayed { private String data; private long expireTime; public DelayedElement(String data, long delayTime) { this.data = data; this.expireTime = System.currentTimeMillis() + delayTime; } public String getData() { return data; } @Override public long getDelay(TimeUnit unit) { return unit.convert(expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return Long.compare(this.getDelay(TimeUnit.MILLISECONDS), o.getDelay(TimeUnit.MILLISECONDS)); } } ``` 在这个示例中,我们定义了一个`DelayedElement`类,它实现了`Delayed`接口,并重写了`getDelay`和`compareTo`方法。`getDelay`方法返回该元素离过期时间还有多少时间,`compareTo`方法用于比较两个元素的顺序。 在`main`方法中,我们首先创建了一个`DelayQueue`对象,并向其中添加了三个元素,分别延时1秒、2秒和3秒。然后我们不断从队列中取出元素,直到队列为空。在取出元素的过程中,由于是按照元素到期时间来排序的,所以最先到期的元素会被最先取出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值