Launch a timed service - Strategies
1 min read

Launch a timed service - Strategies

Launch a timed service - Strategies

An app I am writing at the moment needs to have a periodic timer, i.e. a way to run a bit of code at regular intervals. After digging through different sources, I've found two recommended patterns to code such behaviour:

  1. Using a periodic alarm: Android has the concept of periodic alarms (think an alarm clock you program to ring every day). This seems to me as the most obvious way to implement the functionality described above.
  2. Coming from Javascript world (and not only), an alternative is a self-arming alarm. In effect, the arming code is part of the executed function

Below I'm illustrating the two approaches in pseudocode.

Periodic Alarm

The alarm has a start point and an repeating interval:

void setUp() {
    AlarmManager.setRepeating(
        delayStart,
        interval,
        myCallback);

    // Other code here
}

void myCallback() {
    // do something here
}

The call basically says:

Set up an alarm which will call myCallback periodically every interval and where the first call will happen after delayStart

Re-arming code

The re-arming code splits the alarm setup in two:

void setUp() {
    AlarmManager.setAlarm(
        delayStart,
        myCallback);

    // Other code here
}

void myCallback() {
    AlarmManager.setAlarm(
        interval,
        myCallback);

    // do something here
}

The effect is the same, but the approach is slightly different. I'm more for the former approach as the alarm triggering code is in one place. However, if your app needs to change the alarm interval (e.g. user setting), the latter approach may be more intuitive, as the you only have to set the new interval and programmatically call myCallback().

HTH,