001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.rest.server.sse; 018 019 020import java.io.*; 021import java.time.*; 022import java.util.concurrent.*; 023import java.util.concurrent.atomic.*; 024 025import org.apache.juneau.marshall.sse.*; 026import static org.apache.juneau.commons.utils.Shorts.*; 027 028/** 029 * Scheduled SSE heartbeat. 030 */ 031@SuppressWarnings({ 032 "resource" // start() returns the SseHeartbeat to the caller, who closes it 033}) 034public class SseHeartbeat implements Runnable, AutoCloseable { 035 036 /** 037 * Starts a heartbeat. 038 * 039 * @param scheduler The scheduler. Must not be <jk>null</jk>. 040 * @param writer The writer. Must not be <jk>null</jk>. 041 * @param interval The heartbeat interval. Must not be <jk>null</jk>. 042 * @return The heartbeat handle. 043 */ 044 public static SseHeartbeat start(ScheduledExecutorService scheduler, Writer writer, Duration interval) { 045 var heartbeat = new SseHeartbeat(writer); 046 var i = reqnn("interval", interval).toMillis(); 047 req(i > 0, "interval must be > 0."); 048 heartbeat.future = scheduler.scheduleAtFixedRate(heartbeat, i, i, TimeUnit.MILLISECONDS); 049 return heartbeat; 050 } 051 052 private final Writer writer; 053 private final AtomicBoolean closed; 054 private ScheduledFuture<?> future; 055 056 /** 057 * Constructor. 058 * 059 * @param writer The writer. Must not be <jk>null</jk>. 060 */ 061 public SseHeartbeat(Writer writer) { 062 this.writer = reqnn("writer", writer); 063 closed = new AtomicBoolean(); 064 } 065 066 @Override /* Runnable */ 067 public void run() { 068 if (closed.get()) 069 return; 070 try { 071 SseSerializer.writeComment(writer, "ping"); 072 } catch (IOException e) { 073 close(); 074 } 075 } 076 077 @Override /* AutoCloseable */ 078 public void close() { 079 if (closed.compareAndSet(false, true) && future != null) 080 future.cancel(false); 081 } 082}