Timer.scheduleAtFixedRate does not stop when I call cancel

In onCreate, I run a task that repeats every minute. Here is 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 this code is in onCreate. So, when the application leaves the screen, I see in logcat that the steel timer works, and will not stop if the application is not destroyed. So, in onPause activity, I call myTimer.cancel(); , but it did not help. I still see updates in logcat, even when the application does not appear on the screen. So how to stop timerTask ?

+6
source share
2 answers

Here is your code placed in my file, with a delay of values ​​and a period, so I do not need to wait so long. I launched the application. I see messages in LogCat. I press the home button on my Galaxy S3. Then the messages are stopped 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(); } } 
+4
source

Perhaps, since the stream has already been sent, it starts for the last time. In onLoad, set the variable to true, then in onPause set to false. Then, in the timer task, run your code only if the variable is true.

Log outside the new if statement. If this really works for the last time, then this may be your solution. But if it still works many times after onPause, then do not make my decision.

0
source

All Articles