schedule和scheduleAtFixedRate有什么区别?

编程入门 行业动态 更新时间:2024-10-28 02:24:10
本文介绍了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有什么区别?

本文发布于:2023-11-24 01:27:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   schedule   scheduleAtFixedRate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!