Scheduled Executor Fixed Rate Heartbeat
Run a recurring heartbeat with scheduleAtFixedRate, cancel it from another task, and shut the scheduler down without leaking threads.
Code
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class HeartbeatScheduler {
public static void main(String[] args) throws Exception {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
// fixedRate:按起始时间对齐;fixedDelay:按上次结束对齐
ScheduledFuture<?> heartbeat = scheduler.scheduleAtFixedRate(() -> {
System.out.println("beat at " + System.currentTimeMillis());
}, 0, 200, TimeUnit.MILLISECONDS);
// 5 拍之后由另一个任务取消心跳
scheduler.schedule(() -> {
heartbeat.cancel(false);
System.out.println("heartbeat cancelled");
}, 1200, TimeUnit.MILLISECONDS);
// 等取消生效后关闭;awaitTermination 保证优雅退出
scheduler.shutdown();
if (!scheduler.awaitTermination(3, TimeUnit.SECONDS)) {
scheduler.shutdownNow();
}
System.out.println("scheduler down");
}
}What the code does
Scheduled Executor Fixed Rate Heartbeat comes down to the class HeartbeatScheduler.
Applying it
The demo output is labeled (beat at, heartbeat cancelled, scheduler down), so every printed line maps back to its originating operation.
Statements that matter
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Interactive Tools for This Topic
FAQ
- What does Scheduled Executor Fixed Rate Heartbeat print when run?
- The script runs standalone; its 3 labeled outputs include `beat at`, `heartbeat cancelled`, `scheduler down`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.