I'm developing an application which sends a message to a specific number in a specific period of time. The problem is that it continues sending that message after that period of time. How would I stop the timer after that specific time in order to stop sending that message?
onTick(long millisUntilFinished ) - In this method we have to pass countdown mill seconds after done countdown it will stop Ticking. onFinish() - After finish ticking, if you want to call any methods or callbacks we can do in onFinish(). start() - It is used to call countdown timer.
After start -> make it true; Inside OnTick -> make it true (not actually required, but a double check) Inside OnFinish -> make it false; use the isTimerRunning property to track the status. Show activity on this post. Check if the CountDownTimer is Running and also if the app is running in the background.
delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. (Your IDE should also show it to you automatically) So delay is the time from now till the first execution, and after that it executes every period milliseconds again.
CountDownTimer waitTimer; waitTimer = new CountDownTimer(60000, 300) { public void onTick(long millisUntilFinished) { //called every 300 milliseconds, which could be used to //send messages or some other action } public void onFinish() { //After 60000 milliseconds (60 sec) finish current //if you would like to execute something when time finishes } }.start();
to stop the timer early:
if(waitTimer != null) { waitTimer.cancel(); waitTimer = null; }
and.. we must call "waitTimer.purge()" for the GC. If you don't use Timer anymore, "purge()" !! "purge()" removes all canceled tasks from the task queue.
if(waitTimer != null) { waitTimer.cancel(); waitTimer.purge(); waitTimer = null; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With