问题
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.
回答1:
This would be accomplished with the schedule()
methods (assuming java.util.Timer
is being used). It provides fixed delay as opposed to fixed rate.
回答2:
After some (re)searching, I believe the scheduleWithFixedDelay method of ScheduledExecutorService implements exactly this.
回答3:
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.
来源:https://stackoverflow.com/questions/24754014/how-can-i-schedule-java-tasks-at-guaranteed-fixed-rate-independent-of-task-run