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: 
Use timer task start timer in onStart() and stop it in onStop() 

look at this example

```
CountDownTimer countDownTimerFixed = new CountDownTimer(Time, Tick) {

    @Override
    public void onTick(long millisUntilFinished) {
// this will call every second 
    }

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub
// this will call when timer is go to finish 
        this.start();

    }
};

```

if you need periodic tasks for every 10 mins, pass 10 mins and tick time to countdowntimer
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.