timer.scheduleAtFixedRate does not stop when i call cancel

Daler picture Daler · Jan 10, 2013 · Viewed 15.1k times · Source

At onCreate, I run a task that repeats every minute. Here how I do it:

myTimer = new Timer();
    int delay = 30000;   // delay for 30 sec.
    int period = 600000;  // repeat every 60 sec.
    doThis = new TimerTask() {
      public void run() {

                     Log.v("TImer","repeated");
                     wv.reload();

      }
    };

    myTimer.scheduleAtFixedRate(doThis, delay, period);

All that code is in onCreate. So, when the app goes off from the screen, I can see in logcat that timer steel runs, and will not stop unless the app will be destroyed. So, in onPause of activity I call myTimer.cancel(); but it didnt help. I still can see updates in logcat, even when the app is not on the screen. So, how to stop timerTask?

Answer

Anthony Tietjen picture Anthony Tietjen · Jan 10, 2013

Here is your code put into my file, with the values delay and period tweaked so I don't have to wait so long. I run the app. I see the messages in LogCat. I press the home button on my Galaxy S3. Then the messages stop in LogCat.

public class MainActivity extends Activity {
    Timer myTimer;
    TimerTask doThis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myTimer = new Timer();
        int delay = 0;   // delay for 30 sec.
        int period = 1000;  // repeat every 60 sec.
        doThis = new TimerTask() {
          public void run() {

                         Log.v("TImer","repeated");

          }
        };

        myTimer.scheduleAtFixedRate(doThis, delay, period);
    }

    @Override
    protected void onPause() {
        myTimer.cancel();
        super.onPause();
    }
}