Question: In my activity oncreate method, i have called a service using OnStartCommand(). My requirement is when the user is on the same Activity (when the Activity is visible), a set of code should run repeatedly. (Example .. I should make a web service call and get the response and do some action based on it after regular intervals).

I have put this set of code in this method.

```
@Override
     public int onStartCommand(Intent i, int flags , int startId){

        // Code to be repeated

return Service.START_STICKY;
}

```

But, this is getting executed only once. How to make it run repeatedly from the time the user came to this page till he leaves this page ??

Answer: 
CountDownTimer.cancel() method seems to be not working.

I would recommend you to use Timer instead. It's much more flexible and can be cancelled at any time. It may be something like that:

```
public class MainActivity extends Activity {    
    TextView mTextField;
    long elapsed;
    final static long INTERVAL=1000;
    final static long TIMEOUT=5000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mTextField=(TextView)findViewById(R.id.textview1);

        TimerTask task=new TimerTask(){
            @Override
            public void run() {
                elapsed+=INTERVAL;
                if(elapsed>=TIMEOUT){
                    this.cancel();
                    displayText("finished");
                    return;
                }
                //if(some other conditions)
                //   this.cancel();
                displayText("seconds elapsed: " + elapsed / 1000);
            }
        };
        Timer timer = new Timer();
       timer.scheduleAtFixedRate(task, INTERVAL, INTERVAL);
   }

    private void displayText(final String text){
        this.runOnUiThread(new Runnable(){
            @Override
            public void run() {
                mTextField.setText(text);
            }});
    }
}

```
You can use Timer for the fixed-period execution of a method.

See here is a tutorial on this:

<http://steve.odyfamily.com/?p=12>