public static void main(String[] args) { //创建延迟队列 DelayQueue<DelayQueueUtils> queue = null; if (queue!=null&&!queue.isEmpty()) { //清空延迟队列 queue.clear(); } queue = new DelayQueue<>(); //添加信息到延迟队列 for(int i=0;i<10;i++){ DelayQueueUtils o1 = new DelayQueueUtils(); o1.setUserId("123"+i); o1.setOnlyCode("456"+i); o1.setExpirationTime(DateUtils.parseDate("2023-12-05 16:49:3"+i)); queue.offer(o1); } try { //循环展示队列中数据 Iterator<DelayQueueUtils> iterator = queue.iterator(); while (iterator.hasNext()){ DelayQueueUtils dy = iterator.next(); System.out.println(dy.getUserId()); if("1230".equals(dy.getUserId())) { queue.remove(dy); } } //延迟队列执行过期数据 boolean flag = true; while (flag) { if(!queue.isEmpty()){ DelayQueueUtils take = queue.take(); System.out.println(take.getUserId()+"--"+take.getOnlyCode()+"--"+take.getExpirationTime()); }else{ flag = false; } } } catch (InterruptedException e) { e.printStackTrace(); } }
public class DelayQueueUtils implements Delayed{ private String userId; /** * 编号 */ private String onlyCode; /** * 过期时间 */ private Date expirationTime; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getOnlyCode() { return onlyCode; } public void setOnlyCode(String onlyCode) { this.onlyCode = onlyCode; } public Date getExpirationTime() { return expirationTime; } public void setExpirationTime(Date expirationTime) { this.expirationTime = expirationTime; } /** * 判断过期的策略:过期时间大于等于当前时间就算过期 * * @param unit * @return */ @Override public long getDelay(TimeUnit unit) { return unit.convert(this.expirationTime.getTime() - System.currentTimeMillis(), TimeUnit.NANOSECONDS); } /** * 加入队列的排序规则 * * @param o * @return */ @Override public int compareTo(Delayed o) { DelayQueueUtils orderDelayDto = (DelayQueueUtils) o; long time = orderDelayDto.getExpirationTime().getTime(); long time1 = this.getExpirationTime().getTime(); return time == time1 ? 0 : time < time1 ? 1 : -1; } }