简体   繁体   中英

How can I schedule Java tasks at guaranteed fixed rate, independent of task run time?

java.util.Timer's scheduleAtFixedRate is an obvious alternative if one wants to schedule tasks at a certain interval. However, if your interval is 10 s. and the tasks take more than 10 s. this function will busy-execute anything pending according to the documentation (quote: two or more executions will occur in rapid succession to "catch up."). This is of course a reasonable way to implement it, but it's not necessarily what you want.

Does anyone know about standard functionality in the Java API for scheduling task n+1 <interval> milliseconds after task n, independent of how long time task n took?

I've implemented this functionality myself twice now (two different projects) because it's simply the most correct way to implement it in the cases I've stumbled upon.

You might say this is trivial (and it is) but I hadn't mentioned it if it wasn't a recurring thing.

My main point here is that if the "catching up" strategy is deemed "correct", then my approach here would be equally correct in quite a few cases and I think scheduleAtFixedRate should include an option for it. This isn't a problem for me, I just wanted to see if anyone knew if this was implemented already in the Java API so I don't have to code it now and then.

This would be accomplished with the schedule() methods (assuming java.util.Timer is being used). It provides fixed delay as opposed to fixed rate.

经过一些(重新)搜索后,我相信ScheduledExecutorServicescheduleWithFixedDelay方法正是实现了这一点。

I think this does exactly what you want. Java.util.timer -> schedule(TimerTask task, long delay, long period). This executes with "fixed delay". According to the documentation: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM