java定时器???
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后的意思。
谢谢!!