Repeat a task with a time delay?

后端 未结 12 1410
小蘑菇
小蘑菇 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:31

    Using kotlin and its Coroutine its quite easy, first declare a job in your class (better in your viewModel) like this:

    private var repeatableJob: Job? = null
    

    then when you want to create and start it do this:

    repeatableJob = viewModelScope.launch {
        while (isActive) {
             delay(5_000)
             loadAlbums(iImageAPI, titleHeader, true)
        }
    }
    repeatableJob?.start()
    

    and if you want to finish it:

    repeatableJob?.cancel()
    

    PS: viewModelScope is only available in view models, you can use other Coroutine scopes such as withContext(Dispatchers.IO)

    More information: Here

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:35

    I think the new hotness is to use a ScheduledThreadPoolExecutor. Like so:

    private final ScheduledThreadPoolExecutor executor_ = 
            new ScheduledThreadPoolExecutor(1);
    this.executor_.scheduleWithFixedDelay(new Runnable() {
    @Override
    public void run() {
        update();
        }
    }, 0L, kPeriod, kTimeUnit);
    
    0 讨论(0)
  • 2020-11-22 02:38

    You can use a Handler to post runnable code. This technique is outlined very nicely here: https://guides.codepath.com/android/Repeating-Periodic-Tasks

    0 讨论(0)
  • 2020-11-22 02:40

    Try following example it works !!!

    Use [Handler] in onCreate() method which makes use of postDelayed() method that Causes the Runnable to be added to the message queue, to be run after the specified amount of time elapses that is 0 in given example. 1

    Refer this code :

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
           setContentView(R.layout.main);
        //------------------
        //------------------
        android.os.Handler customHandler = new android.os.Handler();
                customHandler.postDelayed(updateTimerThread, 0);
    }
    
    private Runnable updateTimerThread = new Runnable()
    {
            public void run()
            {
                //write here whaterver you want to repeat
                customHandler.postDelayed(this, 1000);
            }
    };
    

    0 讨论(0)
  • 2020-11-22 02:40

    For people using Kotlin, inazaruk's answer will not work, the IDE will require the variable to be initialized, so instead of using the postDelayed inside the Runnable, we'll use it in an separate method.

    • Initialize your Runnable like this :

      private var myRunnable = Runnable {
          //Do some work
          //Magic happens here ↓
          runDelayedHandler(1000)   }
      
    • Initialize your runDelayedHandler method like this :

       private fun runDelayedHandler(timeToWait : Long) {
          if (!keepRunning) {
              //Stop your handler
              handler.removeCallbacksAndMessages(null)
              //Do something here, this acts like onHandlerStop
          }
          else {
              //Keep it running
              handler.postDelayed(myRunnable, timeToWait)
          }
      }
      
    • As you can see, this approach will make you able to control the lifetime of the task, keeping track of keepRunning and changing it during the lifetime of the application will do the job for you.

    0 讨论(0)
提交回复
热议问题