What is the difference between schedule and scheduleAtFixedRate?

The documentation does explain the difference:

schedule:

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.

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

TTWWWTTWWWTTWWWTT

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

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

The third task starts 5 seconds after the second one.

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

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

TTWWWGGTTWTTWWWTT

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

Leave a Comment