schedule和scheduleAtFixedRate有什么区别? [英] What is the difference between schedule and scheduleAtFixedRate?

查看:274
本文介绍了schedule和scheduleAtFixedRate有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个Timer类的方法有什么区别:

What is the difference between these 2 methods of Timer class :

schedule(TimerTask task, long delay, long period)

scheduleAtFixedRate(TimerTask task, long delay, long period)

文档不能使它们之间的区别变得清楚.

Documentation doesn't make the difference between them clear.

推荐答案

文档确实说明了区别:

时间表:

在固定延迟执行中,相对于上一次执行的实际执行时间安排每次执行.如果执行由于某种原因(例如垃圾回收或其他后台活动)而延迟执行,则随后的执行也将被延迟.

In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.

因此,假设延迟为5秒,并且每个任务花费2秒,您将得到

So, suppose the delay is 5 seconds, and each task takes 2 seconds, you would get

TTWWWTTWWWTTWWWTT

其中T表示1秒钟用于任务执行,而W表示1秒钟等待.

where T means 1 second for the task execution, and W means 1 second waiting.

但是现在假设发生了一个长GC(用G表示)并延迟了第二个任务,那么第三个任务将在第二个任务开始后的5秒后开始,就好像长GC并没有发生:

But now suppose that a long GC (represented by a G) happens and delays the second task, the third one will start 5 seconds after the start of the second one, as if the long GC didn't happen:

TTWWWGGTTWWWTTWWWTT

第三个任务在第二个任务之后5秒开始.

The third task starts 5 seconds after the second one.

scheduleAtFixedRate:

scheduleAtFixedRate:

在定额执行中,相对于初始执行的计划执行时间来计划每个执行.如果执行由于某种原因(例如垃圾回收或其他后台活动)而延迟,则将快速连续发生两个或更多个执行以追赶".

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.".

因此,与上述相同的延迟和相同的GC,您将得到

So, with the same delay as above, and the same GC, you would get

TTWWWGGTTWTTWWWTT

第三个任务任务从第二个任务之后的5秒开始而不是3秒开始追赶.

The third task task starts 3 seconds instead of 5 after the second one, to catch up.

这篇关于schedule和scheduleAtFixedRate有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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