Repeat a task with a time delay?

后端 未结 12 1569
小蘑菇
小蘑菇 2020-11-22 02:14

I have a variable in my code say it is \"status\".

I want to display some text in the application depending on this variable value. This has to be done with a speci

12条回答
  •  耶瑟儿~
    2020-11-22 02:33

    In my case, I had to execute a process if one of these conditions were true: if a previous process was completed or if 5 seconds had already passed. So, I did the following and worked pretty well:

    private Runnable mStatusChecker;
    private Handler mHandler;
    
    class {
    method() {
      mStatusChecker = new Runnable() {
                int times = 0;
                @Override
                public void run() {
                    if (times < 5) {
                        if (process1.isRead()) {
                            executeProcess2();
                        } else {
                            times++;
                            mHandler.postDelayed(mStatusChecker, 1000);
                        }
                    } else {
                        executeProcess2();
                    }
                }
            };
    
            mHandler = new Handler();
            startRepeatingTask();
    }
    
        void startRepeatingTask() {
           mStatusChecker.run();
        }
    
        void stopRepeatingTask() {
            mHandler.removeCallbacks(mStatusChecker);
        }
    
    
    }
    

    If process1 is read, it executes process2. If not, it increments the variable times, and make the Handler be executed after one second. It maintains a loop until process1 is read or times is 5. When times is 5, it means that 5 seconds passed and in each second, the if clause of process1.isRead() is executed.

提交回复
热议问题