0

I'm using Timer() due to its accuracy but works in the same was as PostDelayed Handler. It's called only once. Here is the Timer code:

    public void setWFT() {
        WFT = new Timer();
        WFT.schedule(new TimerTask() {          
            @Override
            public void run() {
                WFTTimerMethod();
            }
        }, 60000); // 60 seconds delay
    }

    private void WFTTimerMethod() {
        this.runOnUiThread(Timer_Tick);
    }

    private Runnable Timer_Tick = new Runnable() {
        public void run() {
            // My commands here
        }
    };

This only calls run() once after 60 seconds once the Timer is started. Sometimes, I have to cancel the Timer to Update the delay (replace the "60000" value). To start the Timer again, I simply recreate the Timer by calling WFT() again with the new delay value.

Problem is, when I cancel the timer using:

WFT.cancel();
WFT.purge();

The Timer does not start. the run() doesn't execute when it's supposed to. So my question is do I use cancel() and purge() or just cancel()?

Thanks

KickAss
  • 4,210
  • 8
  • 33
  • 41

2 Answers2

3

From the Java API on purge():

Most programs will have no need to call this method. It is designed for use by the rare application that cancels a large number of tasks. Calling this method trades time for space: the runtime of the method may be proportional to n + c log n, where n is the number of tasks in the queue and c is the number of cancelled tasks.

So you only need to call cancel()

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
  • Also, as my Timer() acts like a PostDelayed and only called once 60 seconds in the future, will cancel() cancel and destroy the timer before it's execution or will it have no effect on my Timer() as it's a only due to be executed once? – KickAss Apr 17 '13 at 13:55
  • From the same API link: `cancel()` "Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it." So it will cancel all future scheduled events. – Bryan Denny Apr 17 '13 at 13:58
0

from cancel() documentation :

No more tasks may be scheduled on this Timer.

njzk2
  • 38,969
  • 7
  • 69
  • 107