自定义延迟队列
import lombok.Data;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @Description: 实现Delayed接口,重写getDelay()和compareTo()方法
*/
@Data
public class MyDelayQueue implements Delayed {
private long time;
private String desc;
public MyDelayQueue(long time, String desc) {
this.time = time * 1000 + System.currentTimeMillis();
this.desc = desc;
}
//判断是否过期
@Override
public long getDelay(TimeUnit unit) {
return time - System.currentTimeMillis();
}
//任务排序
@Override
public int compareTo(Delayed o) {
MyDelayQueue delayTask = (MyDelayQueue) o;
return time - delayTask.getTime() <= 0 ? -1 : 1;
}
}
测试
import com.alibaba.fastjson.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.DelayQueue;
/**
* @Description:测试上面实现的延迟队列
*/
public class TestMyDelayQueue {
public static void main(String[] args) throws InterruptedException {
DelayQueue<MyDelayQueue> queue = new DelayQueue<>();
queue.put(new MyDelayQueue(10, "10s后到期"));
queue.put(new MyDelayQueue(30, "30s后到期"));
queue.put(new MyDelayQueue(20, "20s后到期"));
System.out.println("任务开始执行时间:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
while (queue.size() > 0) {
MyDelayQueue delayTask = queue.take();
if (Objects.nonNull(delayTask)) {
System.out.println("过期任务:" + delayTask.getDesc() + "过期时间:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(delayTask.getTime())));
}
}
}
}
控制台打印
任务开始执行时间:2022-11-10 01:06:47
过期任务:10s后到期过期时间:2022-11-10 01:06:57
过期任务:20s后到期过期时间:2022-11-10 01:07:07
过期任务:30s后到期过期时间:2022-11-10 01:07:17
Process finished with exit code 0