简体   繁体   English

Android Java Timer()

[英]Android Java Timer()

I'm using Timer() due to its accuracy but works in the same was as PostDelayed Handler. 由于其准确性,我使用Timer(),但其工作原理与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. 计时器启动后,仅在60秒后调用一次run()。 Sometimes, I have to cancel the Timer to Update the delay (replace the "60000" value). 有时,我必须取消计时器以更新延迟(替换“ 60000”值)。 To start the Timer again, I simply recreate the Timer by calling WFT() again with the new delay value. 要再次启动计时器,我只需通过使用新的延迟值再次调用WFT()来重新创建计时器。

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. run()在应该执行的时候不执行。 So my question is do I use cancel() and purge() or just cancel()? 所以我的问题是我要使用cancel()和purge()还是只使用cancel()?

Thanks 谢谢

From the Java API on purge() : purge() 的Java API中

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. 调用此方法会以时间换取空间:该方法的运行时间可能与n + c log n成正比,其中n是队列中的任务数,而c是已取消任务的数。

So you only need to call cancel() 所以你只需要调用cancel()

from cancel() documentation : cancel()文档中:

No more tasks may be scheduled on this Timer. 不能在此计时器上安排更多任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM