2010-11-23 55 views
3

我已經完成了大量的工作來從Web服務中檢索一些數據,但現在有調度請求的問題,我不確定從哪裏開始。如何執行任務調度?

我聽JMS隊列事件並在接收到事件的我需要一個持續時間後,Web服務的請求。持續時間取決於事件屬性。如果Web服務返回false,我需要繼續安排請求,直到它返回true。

我想創建於在收到一個事件或錯誤的響應隊列查找請求,但這似乎並不理想 - 我會不斷地消費消息,檢查時間,看看是否請求如果沒有的話,應該把它還給隊列。

如果任何人有關於如何實現這樣一個問題,我會很感激的建議。

回答

0

我決定去與已在第3版中引入,提供統籌,調度基於時間和間隔都時刻,如果需要更多的定製它有一個cron選項​​。我沒有深入探討Quartz可以實現的深度,但它也提供了與Quartz的整合。

5

首先,確保你保持的事件隊列在其所需要執行的順序。這將確保您只需查看隊列的頭部即可查看應安排下一個事件的時間。你可以用這個PriorityQueue

處理事件的線程將輪詢該隊列中的項目並處理它們。查看頭部項目並查看下一個事件何時需要運行。選擇一個對象用作鎖定對象,並讓主線程在該對象上調用Object.wait(long),將該方法傳遞給毫秒數,直到需要運行下一個事件。

如果一個新的線程時,它將在適當的位置添加到隊列中。如果該項目位於隊列的頭部,這意味着線程需要儘快喚醒。在鎖對象上調用Object.notifyAll()以喚醒處理線程。它會看到沒有任何東西需要處理,並在適當的時間內重新入睡。

 
public class ProcessingQueue extends Thread { 

    private PriorityQueue<Task> tasks; 

    private volatile boolean isRunning = true; 

    public void addTask(Task t) { 
    synchronized (this.tasks) { 
     this.tasks.offer(t); 
     // this call requires synchronization to this.tasks 
     this.tasks.notifyAll(); 
    } 
    } 

    public void shutdown() { 
    this.isRunning = false; 
    synchronized (this.tasks) { 
     this.notifyAll(); 
    } 
    } 

    public void run() { 
    while (this.isRunning) { 
     synchronized (this.tasks) { 
     Task t = this.tasks.peek(); 
     // by default, if there are no tasks, this will wake every 60 seconds 
     long millisToSleep = 60000; 
     // getExecuteMillis() should return the time, in milliseconds, for execution 
     if (t != null) millisToSleep = t.getExecuteMillis() - System.currentTimeMillis(); 
     if (millisToSleep > 0) { 
      try { 
      // this line requires synchronization to this.tasks 
      // and the lock is removed while it waits 
      this.tasks.wait(millisToSleep); 
      } catch (InterruptedException e) { 
      } 
     } 
     t = this.tasks.poll(); 
     if (t != null) { 
      t.execute(); 
     } 
     } 
    } 
    } 
} 
+0

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/DelayQueue.html看看Java的延遲隊列。非常適合基於時間的任務隊列。這裏是源代碼http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/concurrent/DelayQueue.java#DelayQueue.take%28%29 – Anshul 2015-12-06 10:24:48