Search code examples
androidhandleralarmmanager

Execute code at specific time: Handler? AlarmManager?


I need to execute code at intervals, sometimes 10 seconds, sometimes 5 minutes. The code should be executed at exact 10 seconds from start, then at exact 5 minutes and 10 seconds from start, etc.
A Chronometer is ticking along from the start, so the execution time must be accurate.

Using Handler.postDelayed does not work, because the code to execute could take some time. The next execution of the code could be late when that happens.

When I wanted to implement AlarmManager, I saw the note

The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

So I'm a bit confused, how should I do this to guarantee correct execution?


Solution

  • As Chris stated, there's no such thing as exact timing in Android.

    But you could try it like this to come near realtime...

    some Pseudocode for waiting 5s:

    class mJob implements Runnable{
       public void run(){
          while(System.currentTimeMillis()<myExactTime){ //poll for your time
             Thread.sleep(1);
          }
          //Ok, we are as near as we'll ever get
          //call here your 'realtime' function or whatever you need
       }
    }
    
     mHandler.postDelayed(mJob,4950); //the closer to 5000, the better for the cpu but you could miss your `myExactTime`
    

    I don't now how exact this is, you'll just have to try it. But I see no other way to become more 'realtime' with the normal SDK. You could even remove the sleep(1) to become even closer to your myExactTime.

    For the next call use something like this (scratch):

    nextCallDelayInMillis = starttimeInMillis+No1_Delay+No2_Delay-System.currentTimeMillis();