2017-02-28 15 views
3

目前,我設計一個股票市場的應用程序有以下要求Interrrupt-能夠ScheduledExecutorService的Android中

  • 1)掃描股價反覆,有一個固定的睡眠時間。 2)能隨時中斷睡眠。這是因爲當用戶添加新的股票時,我們需要從睡眠中醒來並立即掃描。

此前,我使用裸骨Thread,以充分滿足上述2個要求。

private class StockMonitor extends Thread { 
    @Override 
    public void run() { 
     final Thread thisThread = Thread.currentThread(); 

     while (thisThread == thread) { 

      // Fetch stock prices... 

      try { 
       Thread.sleep(MIN_DELAY); 
      } catch (java.lang.InterruptedException exp) { 
       if (false == refreshed()) { 
        /* Exit the primary fail safe loop. */ 
        thread = null;        
        break; 
       } 
      } 
     } 
    } 

    public synchronized void refresh() {   
     isRefresh = true; 
     interrupt(); 
    } 

    private synchronized boolean refreshed() { 
     if (isRefresh) { 
      isRefresh = false; 
      // Interrupted status of the thread is cleared. 
      interrupted(); 
      return true; 
     } 
     return false; 
    } 
} 

當我想執行要求(2)時,我會打電話給refresh。線程將被喚醒,並立即執行任務。

不過,我覺得很難維護這樣的裸骨代碼,並且容易出錯。我想要使​​用ScheduledExecutorService。但是,我沒有能力將Thread從睡眠狀態中喚醒,並立即執行任務。

我想知道,Android中是否有任何類,它使我能夠執行定期任務,如ScheduledExecutorService?但有能力喚醒線程從睡眠狀態,並立即執行工作。

回答

1

這是我的解決方案ScheduledThreadPoolExecutor。要取消現有任務,請從scheduleAtFixedRate()返回的Future對象上發出future.cancel()。然後再撥打scheduleAtFixedRate()並將initial delay設爲0.

class HiTask implements Runnable { 
    @Override 
    public void run() { 
     System.out.println("Say Hi!"); 
    } 
} 

// periodically execute task in every 100 ms, without initial delay time 

ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1); 

long initialDelay = 0; 
long period = 100; 

ScheduledFuture<?> future1 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS); 


// to trigger task execution immediately 

boolean success = future.cancel(true); // mayInterruptIfRunning = true: interrupt thread even task has already started 

ScheduledFuture<?> future2 = exec.scheduleAtFixedRate(new HiTask(), initialDelay, period, TimeUnit.MILLISECONDS); 
0

選項你有ScheduledExecutorService

  • submit()相同的任務,又在那一刻,你需要的數據被刷新。如果將立即執行(並且只有一次)。可能的缺點:如果發生這種情況非常接近預定的執行時間,則可以在兩次掃描之間進行兩次掃描。
  • cancel()當前需要刷新數據的任務,submit()立即執行,schedule()重複執行。

請注意,未經處理的任務中發生的任何異常都會取消將來的執行。如何解決這個問題在How to reschedule a task using a ScheduledExecutorService?得到解答。

ExecutorService不是持久的(即不能在設備重新啓動後存活)。我不知道這對你是否有問題。如果有專門的後臺任務執行於Android庫:

你將不得不申請上述相同的解決方法。