java定时器???

FengPrince 2012-10-06 09:40:24

TimerTask中scheduledExecutionTime()API描述是这样的:
Returns the scheduled execution time of the most recent actual execution of this task. (If this method is invoked while task execution is in progress, the return value is the scheduled execution time of the ongoing task execution.)

This method is typically invoked from within a task's run method, to determine whether the current execution of the task is sufficiently timely to warrant performing the scheduled activity:

public void run() {
if (System.currentTimeMillis() - scheduledExecutionTime() >=
MAX_TARDINESS)
return; // Too late; skip this execution.
// Perform the task
}


This method is typically not used in conjunction with fixed-delay execution repeating tasks, as their scheduled execution times are allowed to drift over time, and so are not terribly significant.

我比较困惑的是System.currentTimeMillis() - scheduledExecutionTime()这一用法。
scheduled execution time是不是与actual execution time不同??
假设在时刻t,TimerTask第一次被调用执行,然后按照Timer类的scheduleAtFixedRate(task,t,delt)进行fixed-rate的重复执行。那么scheduled execution time应该是t+delt,t+2*delt,...,t+n*delt,而且是确定的,只要到这个时间点就会发生scheduled execution(这里不考虑时钟的绝对精确性问题),至于task实际的执行时间则是未知的:比如在t+delt时刻发生了scheduled execution,但由于某种原因,task调用被推迟了,到t+1.5*delt时刻才真正执行。
那么在这种情况下scheduledExecutionTime()的返回值对应的t+delt而非t+1.5*delt。假设MAX_TARDINESS=0.2delt,这时System.currentTimeMillis() - scheduledExecutionTime()=0.5delt,超过了最大延迟0.2delt,然后task任务就应该被迫放弃本次执行。

不知道,我的理解对与不对,求大牛指点。。。

PS: API SPECS中有一句话是:The return value is undefined if the task has yet to commence its first execution.不明白这句话想表达什么意思。我的理解是将if换成when后的意思。

谢谢!!
...全文
171 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
FengPrince 2012-10-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 的回复:]

你的理解是对的

不过,在这里,人家只是列举一个对方法scheduledExecutionTime()使用的例子,没有多大实际意义,在Timer里如何调度任务,完全由Timer自己决定,只是借助于TimerTask存储一下数据(执行时间等)而已。

要实现他注释里那种最大延时的功能,需要自己具体实现,注释中的例子就是一个最基本的方法。
[/Quote]
嗯,十分感谢。。。
oO临时工Oo 2012-10-08
  • 打赏
  • 举报
回复
你的理解是对的

不过,在这里,人家只是列举一个对方法scheduledExecutionTime()使用的例子,没有多大实际意义,在Timer里如何调度任务,完全由Timer自己决定,只是借助于TimerTask存储一下数据(执行时间等)而已。

要实现他注释里那种最大延时的功能,需要自己具体实现,注释中的例子就是一个最基本的方法。
FengPrince 2012-10-07
  • 打赏
  • 举报
回复
还没人回答?
那些复制中文翻译的就不要回复了。。。
huntor 2012-10-06
  • 打赏
  • 举报
回复
scheduledExecutionTime
public long scheduledExecutionTime()返回此任务最近实际 执行的已安排 执行时间。(如果在任务执行过程中调用此方法,则返回值为此任务执行的已安排执行时间。)
通常从一个任务的 run 方法中调用此方法,以确定当前任务执行是否能充分及时地保证完成已安排活动:

public void run() {
if (System.currentTimeMillis() - scheduledExecutionTime() >=
MAX_TARDINESS)
return; // Too late; skip this execution.
// Perform the task
}
通常,此方法不 与固定延迟执行 的重复任务一起使用,因为其已安排执行时间允许随时间浮动,所以毫无意义。

返回:
最近发生此任务执行安排的时间,采用 Date.getTime() 返回的格式。如果任务还未开始其首次执行,则返回值不确定。
另请参见:
Date.getTime()
FengPrince 2012-10-06
  • 打赏
  • 举报
回复
自己顶起。。。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧