DelayQueue的特點就是插入Queue中的資料可以按照自定義的delay時間進行排序,只有delay時間小于0的元素才能夠被取出,
這樣子,只要開啟一個執行緒回圈從DelayQueue中取值執行,就可以達到想要的效果
定義
-
執行的任務類
public abstract class Task implements Delayed, Runnable{ private String id = ""; private long start = 0; /** * @param id id * @param delayInMilliseconds 延時時間(單位:毫秒) */ public Task(String id, long delayInMilliseconds){ this.id = id; this.start = System.currentTimeMillis() + delayInMilliseconds; } public String getId() { return id; } @Override public long getDelay(TimeUnit unit) { long diff = this.start - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed o) { return Ints.saturatedCast(this.start - ((Task) o).start); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null) return false; if (!(o instanceof Task)) { return false; } Task t = (Task)o; return this.id.equals(t.getId()); } @Override public int hashCode() { return this.id.hashCode(); } } -
任務處理類
@Component public class TaskService { private TaskService taskService; // Task是自定義任務類,public abstract class Task implements Delayed, Runnable private DelayQueue<Task> delayQueue = new DelayQueue<Task>(); // 被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,并且只會被服務器執行一次 @PostConstruct private void init() { taskService = this; // 開執行緒死回圈執行任務 new Thread(() -> { while (true) { try { Runnable task = delayQueue.take(); task.run(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } // 添加任務 public void addTask(Task task){ if(delayQueue.contains(task)){ return; } delayQueue.add(task); } public void removeTask(Task task){ delayQueue.remove(task); } }
使用
-
新建自定義的任務類,需要繼承Task
private class DemoTask extends Task { DemoTask(String id, long delayInMilliseconds){ super(id, delayInMilliseconds); } @Override public void run() { DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String now = df.format(LocalDateTime.now()); System.out.println("task id=" + this.getId() + " at time=" + now); } } -
使用
taskService.addTask(new DemoTask("1", 3000));
代碼來源:
https://github.com/linlinjava/litemall
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/472354.html
標籤:其他
下一篇:Java實作3DES加密
