示例代码
@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);
}
}
}