timer.scheduleAtFixedRate does not stop when i call cancel

16,466

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();
    }
}
Share:
16,466
Daler
Author by

Daler

Im an Android developer that wants finally to finish a one little project and put it in play market, so far it seems difficult for me. Well, i will not give up. OK)

Updated on July 26, 2022

Comments

  • Daler
    Daler almost 2 years

    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?

  • Anthony Tietjen
    Anthony Tietjen over 11 years
    Your code works for me, except I took of wv.reload(); -- Not sure what you are doing in that method. Is it something that would cause the app to start again?
  • Anthony Tietjen
    Anthony Tietjen over 11 years
    Also, can you put a Log.v on your onPause method to make sure it is actually getting fired?
  • Daler
    Daler over 11 years
    wv.reload, i just reload a webview. strange that it works for you
  • Anthony Tietjen
    Anthony Tietjen over 11 years
    Strange. Does Log.v show anything in your onPause method? If not, I think it might be spelled wrong, or maybe your P is not upper case or something else out of place -- so it is not actually being called.