Scheduled Fixed Rate Versus Fixed Delay
scheduleAtFixedRate keeps a steady start-time cadence while scheduleWithFixedDelay waits that long after each run, so task cost stretches the gap.
Code
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SchedulerCadence {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
AtomicInteger rateRuns = new AtomicInteger();
AtomicInteger delayRuns = new AtomicInteger();
// scheduleAtFixedRate:对齐固定开始节奏;任务耗时 200ms 不顺延下一轮
var rate = pool.scheduleAtFixedRate(() -> {
rateRuns.incrementAndGet();
sleepUnchecked(200);
}, 0, 500, TimeUnit.MILLISECONDS);
// scheduleWithFixedDelay:上一轮结束后再等 500ms;间隔被任务耗时拉长
var delay = pool.scheduleWithFixedDelay(() -> {
delayRuns.incrementAndGet();
sleepUnchecked(200);
}, 0, 500, TimeUnit.MILLISECONDS);
Thread.sleep(2000);
rate.cancel(false);
delay.cancel(false);
pool.shutdown();
pool.awaitTermination(1, TimeUnit.SECONDS);
// 实测次数会随机器计时波动,但 rate 恒多于 delay
System.out.println("fixed rate runs: " + rateRuns.get());
System.out.println("fixed delay runs: " + delayRuns.get());
}
static void sleepUnchecked(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}What runs when
Structurally, expect the class SchedulerCadence and the function sleepUnchecked and nothing else.
Points of care
- Nothing beyond the language’s own toolchain is required.
Applying it
The signature at the center: static void sleepUnchecked(long ms)
The demo output is labeled (fixed rate runs:, fixed delay runs:); each label names the call that printed it.
The sequence sleepUnchecked lives in main; running the file triggers it.
Statements that matter
ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
Thread.currentThread().interrupt();
Thread.sleep(2000);
Interactive Tools for This Topic
FAQ
- What does Scheduled Fixed Rate Versus Fixed Delay print when run?
- Invoke the file as-is — the `fixed rate runs:`, `fixed delay runs:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.