如何每秒运行一次任务10秒。

时间:2014-05-22 05:54:13

标签: java android timer android-handler

我有以下代码每秒运行一个任务,但我也希望任务在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); 

4 个答案:

答案 0 :(得分:0)

使用带有布尔变量的While循环并将此变量设置为true,然后您可以计算任务运行的次数,并在每次运行后停止任务1秒,但可能会发生1秒的延迟因为线程调度而不是一秒。

所以你可以用时间来计算和停止while循环。 保存您的治疗时间,每1秒钟执行一次任务。在你的Thread终止10次之后,要么通过while循环终止线程,要么将boolean变量设置为false。

答案 1 :(得分:0)

如果您可以拥有外部依赖项,请尝试使用Timer类或Quartz调度程序,而不是在您自己的应用程序中编写调度和线程逻辑。

答案 2 :(得分:0)

为了使用计数器,你可以将它包装在这样的函数中:

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);

答案 3 :(得分: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);