github.com/nya3jp/tast@v0.0.0-20230601000426-85c8e4d83a9b/src/go.chromium.org/tast/core/internal/bundle/heartbeat.go (about) 1 // Copyright 2021 The ChromiumOS Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package bundle 6 7 import ( 8 "time" 9 ) 10 11 // heartbeatWriter writes heartbeat messages periodically to eventWriter. 12 type heartbeatWriter struct { 13 fin chan struct{} // sending a message to this channel stops the background goroutine 14 } 15 16 // newHeartbeatWriter constructs a new heartbeatWriter for ew. 17 // Stop must be called after use to stop the background goroutine. 18 func newHeartbeatWriter(ew *eventWriter) *heartbeatWriter { 19 const interval = time.Second 20 21 fin := make(chan struct{}) 22 23 go func() { 24 defer close(fin) 25 26 tick := time.NewTicker(interval) 27 defer tick.Stop() 28 29 ew.Heartbeat() 30 for { 31 select { 32 case <-tick.C: 33 ew.Heartbeat() 34 case <-fin: 35 return 36 } 37 } 38 }() 39 40 return &heartbeatWriter{fin: fin} 41 } 42 43 // Stop stops the background goroutine to write heartbeat messages. 44 // Once this method returns, heartbeat messages are no longer written. 45 // Stop must be called exactly once; the behavior on calling it multiple times 46 // is undefined. 47 func (w *heartbeatWriter) Stop() { 48 // Since the channel capacity is 0, the background goroutine will never 49 // write further heartbeat messages once this send finishes. 50 w.fin <- struct{}{} 51 }