簡體   English   中英

如何每秒運行任務10秒鍾。

[英]How to run a task every second for 10 seconds.

我有以下代碼每秒運行一個任務,但我也希望任務在10秒后停止。 可以使用我正在使用的處理程序來實現此邏輯嗎? 我試過用while循環實現一個計數器,但無法正常工作

mHandler = new Handler();
mUpdateUI = new Runnable() {
    public void run() {
        mVistaInspectionDate = HousingFragment.getVistaInspectionDate();
        mVistaInspectionDateTextView.setText(mVistaInspectionDate);     

        if (mVistaInspectionDate != null) {
            mHandler.removeCallbacks(mUpdateUI);
        }
            mHandler.postDelayed(mUpdateUI, 1000); // 1 second
    }
};  

mHandler.post(mUpdateUI); 

使用帶有布爾變量的While循環並將此變量設置為true,那么您可以計算任務運行了多少次,並在每次運行后停止任務1秒鍾,但是可能會延遲1秒鍾而不是1秒鍾由於線程隱藏。

因此,您可以使用時間來計數並停止while循環。 節省您的當前時間,每1秒鍾將執行一次任務。 在線程終止10次之后,可以在while循環中終止線程,也可以將布爾變量設置為false。

如果可以有外部依賴項,請嘗試使用Timer類或Quartz調度程序,而不要在自己的應用程序中編碼調度和線程邏輯。

為了使用計數器,您可以將其包裝在如下函數中:

private void postDelayedWrapped(final int counter, int delay) {
    if (counter <= 0) return;
    mUpdateUI = new Runnable() {
        public void run() {
            mVistaInspectionDate = HousingFragment.getVistaInspectionDate();
            mVistaInspectionDateTextView.setText(mVistaInspectionDate);

            if (mVistaInspectionDate != null) {
                mHandler.removeCallbacks(mUpdateUI); //necessary?
            }
            postDelayedWrapped(counter - 1, 1000);
        }
    };

    mHandler.postDelayed(mUpdateUI, delay);
}

您可以這樣開始:

mHandler = new Handler();
postDelayedWrapped(10,0);

如何子類化Handler類並使用此類的實例來跟蹤postDelayed()被調用了多少次呢?

   public class MyHandler extends Handler {
        private int maxTimes;
        private int currentTimes; 
        private Runnable runner;
        public Handler(int maxTimes) {
              this.maxTimes = maxTimes;
        }

        @Override
        public void post(Runnable runner) {
              this.runner = runner;
        }

        @Override
        public void postDelayed(Runnable runner,long ms) {
               if (currentTimes == maxTimes) {
                    this.removeCallbacks(runner);
               } else {
                    super.postDelayed(runner,ms);
                    currentTimes++;
               }
        } 


   }

   mHandler = new MyHandler(10);//using subclass instance
   //from here on is the same as the original code.
   mUpdateUI = new Runnable() {
   public void run() {
      mVistaInspectionDate = HousingFragment.getVistaInspectionDate();
      mVistaInspectionDateTextView.setText(mVistaInspectionDate);     

      if (mVistaInspectionDate != null) {
          mHandler.removeCallbacks(mUpdateUI);
      }
         mHandler.postDelayed(mUpdateUI, 1000); // 1 second
    }
  };  

  mHandler.post(mUpdateUI); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM