Android的计时器问题 [英] android timer question

查看:181
本文介绍了Android的计时器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我构建会以固定的时间周期(例如每30分钟)执行code块的应用程序。我想这期间要严格,我的意思是,我想被保证的期限将是30分钟,不是28分钟或当操作系统whants执行它。

Hello I am building an application that is going to execute a block of code at fixed periods of time (e.g. every 30 minutes). I would like that period to be strict,what I mean is that I would like to be guaranteed that the period will be 30 minutes and not 28 minutes or whenever the os whants to execute it.

我有一个Timer对象,并用它如下:

I have a Timer object and use it as follows:

定时器=新的Timer();
timer.scheduleAtFixedRate(新GetLastLocation(),0,this.getInterval());

其中,GetLastLocation是处理类至极扩展的TimerTask。
这工作得很好,但我希望能够改变的时间间隔,有什么我目前做的是利用两次和timer.scheduleAtFixedRate变化的时间间隔参数可以说newInterval,但我认为这是仅仅有两个定时器执行每间隔新
现在的时间间隔,我是不是正确的?

timer=new Timer(); timer.scheduleAtFixedRate(new GetLastLocation(), 0, this.getInterval()); where GetLastLocation is the handler class wich extends TimerTask. This works fine,but I would like to be able to change the interval,what I am currently doing is using timer.scheduleAtFixedRate twice and changing the interval parameter to lets say a newInterval but I think that this is just having two timers execute every interval and new Interval now, am I correct?

我也有)试图取消计时器,然后使用该方法scheduleAtFixedRate(不过,这将引发如文档中所述例外。

also I have tries cancelling the timer and then using the the method scheduleAtFixedRate() but this throws an exception as stated in the documentation.

我能做些什么来解决这个问题?
至于maxsap

what can I do to fix this? regards maxsap

推荐答案

您无法在其上已经取消或计划计时器时间表。您需要创建一个新的计时器的

you can not schedule on a timer which was already cancelled or scheduled. You need to create a new timer for that.

Timer timer;
synchronized void setupTimer(long duration){
  if(timer != null) {
    timer.cancel();
    timer = null;
  }
  timer = new Timer();
  timer.scheduleAtFixedRate(new GetLastLocation(), 0, duration);
}

现在,您可以拨打setupTimer每当要改变定时器结果PS的持续时间:在的固定速率执行,每次执行相对于初始执行的安排执行时间安排。如果一个执行被延迟,因任何原因(如垃圾回收或其他后台活动),将出现两个或两个以上执行快速连续赶上。从长远来看,执行的频率将是完全倒数指定时间内(假设系统时钟底层的Object.wait(长)是准确的)的。

Now you can call setupTimer whenever you want to change the duration of the timer.
PS: In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

这篇关于Android的计时器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆