Java定时器下次执行时间
Janitor 是一个每天凌晨 3 点运行的计时器。
Timer janitorTimer = new Timer();
TimerTask janitorWorker = new Janitor(); // Extending TimerTask
long delay = TimeUtils.getMillisUntilTomorrowAt( 3L * 3600000L); // Does what it says
janitorTimer.scheduleAtFixedRate( janitorWorker, delay, 24L * 3600000L);
在某个时间点,我想知道下次 janitorWorker 执行时间。
在 Timer 或 TimerTask 中找不到任何相关内容。 感觉有些事情应该已经知道了。
Meet Janitor, a timer that runs everyday at 3am.
Timer janitorTimer = new Timer();
TimerTask janitorWorker = new Janitor(); // Extending TimerTask
long delay = TimeUtils.getMillisUntilTomorrowAt( 3L * 3600000L); // Does what it says
janitorTimer.scheduleAtFixedRate( janitorWorker, delay, 24L * 3600000L);
At certain point in time I would like to know when is next janitorWorker execution.
Couldn't find anything relevant in Timer nor TimerTask.
Feels that something either should already know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 TimerTask 的实现中,您可以公开 nextExecutionTime,然后将其与当前时间进行比较,请参阅 Timer 中的 mainLoop
In your implementation of
TimerTask
you could expose the thenextExecutionTime
, and then comapre that to the current time, see themainLoop
inTimer
如果任务尚未执行,方法 scheduledExecutionTime 未定义。但是,在我的应用程序中,安排了一次执行的任务,该方法实际上返回执行之前和之后的计划时间。
注意 此行为是特定于设备的且未记录。因此,这种方法应该针对每个设备进行验证,并且不能一般推荐。
In the case when task hasn't executed yet, method scheduledExecutionTime is undefined. However, in my application, where once-executing task is scheduled, this method in fact returns scheduled time both before and after executing.
Note This behaviour is device-specific and non-documented. So, this approach should be verified for each device and cannot be recommended in general.
在 TimerTask 中,存在一个名为
scheduledExecutionTime()
。它的作用是:参考: http://docs .oracle.com/javase/6/docs/api/java/util/TimerTask.html#scheduledExecutionTime%28%29
更新:
这是一种新方法。
因为它具有固定速率,所以您可以调用
scheduledExecutionTime()
添加 fixedRate 值,然后推断 nextExecutionTime。In TimerTask, exists a method called
scheduledExecutionTime()
. What it does is:Reference: http://docs.oracle.com/javase/6/docs/api/java/util/TimerTask.html#scheduledExecutionTime%28%29
UPDATE:
Here is a new way.
Because it has a fixed rate, what you could do is call
scheduledExecutionTime()
add to it the fixedRate value and you then deduce the nextExecutionTime.