Question: I need to perform some periodic tasks as long as an **activity is in the foreground only** (I do not need any processing when the app is asleep). There seem to be two options

1. [Intent Service with Alarm Manager / PendingIntent / BroadcastReceiver](https://github.com/codepath/android_guides/wiki/Starting-Background-Services)
2. ScheduledThreadPoolExecutor

Please provide typical scenarios when either of these should be used, and pros/cons if any.

Answer: 
That depends on whether you want to couple this background process with a specific Activity. `ScheduledThreadPoolExecutor` is technically just a ExecutorService with schedule. It is or should be coupled with Activity lifecycle (e.g stop on onPause, start in onStart). Service is not. It can keep running outside the Activity or even Application scope. Any Activity can communicate with it through `ResultReceiver`.
I think you should use light weight single background thread for the same.

```
Thread thread = new Thread() {
@Override
public void run() {
    try {
        while(true) {

            //put you code here

            sleep(1000);

        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
  }
};

thread.start();

```

after that when activity goes in background some thing like in onStop() method stop this thread using,`thread.stop();`

And if you are going to perform UI related changes then us runOnUiThread. Because you can not perform UI related change from background thread.