I have the following code for a Timer that counts down from 3 seconds
The problem is that it feeds back over and over again and I don't see a way to stop it.
Can someone explain to me how it works and why the "timer3.cancel()" statement doesn't work?
//método de cuenta atrás
private void time3() {
//instancio el Timer
timer3 = new Timer();
timer3.schedule(new TimerTask() {
//inicia el timer
public void run() {
//al valor inicial de la variable, que he puesto en 4, le descuento 1
midTime3--;
//calculo la operación para trabajar en segundos
long ss3 = midTime3 % 60;
//si el segundo es cero
if (ss3 == 0) {
//borro el texto del textView
txtRelojEjercicio2.setText("");
//Vuelvo a darle el valor de 4 a la variable, pues se volverá a llamar al método en breve
midTime3 = 4;
//cancelo en Timer3 en marcha
//lo que deseo es detener el Timer hasta que que vuelva a ser llamado el método
timer3.cancel();
}
//si el segundo está entre 4 y 1
else if ((ss3 < 5) && (ss3 > 0)) {
//escribo la cuenta atrás en el TextView
txtRelojEjercicio2.setText("00:0" + ss3 + "");
}
}
//argumentos del timer para que se ejecute cada segundo
}, 0, 1000);
}
I want to stop the timer, but it restarts over and over again
Can someone shed some light on this for me?
Thank you
To create a Timer that is executed only once, it is done in this way, if you notice, there is only one parameter that indicates the time that will elapse for the task to be executed:
In order for your timer to run only once you should use this constructor:
In your case you are using a different constructor which would be executed repeatedly every second.
So for it to run only once after 1 second, it should be defined like this: