@@ -23,8 +23,7 @@ type LatencyMeasurer struct {
23
23
// background measurement members
24
24
collections atomic.Int64
25
25
last atomic.Value
26
- asyncTick * time.Ticker
27
- stop chan struct {}
26
+ asyncCancel context.CancelCauseFunc
28
27
}
29
28
30
29
type LatencyMeasurement struct {
@@ -39,7 +38,6 @@ func NewLatencyMeasurer(logger slog.Logger) *LatencyMeasurer {
39
38
return & LatencyMeasurer {
40
39
channel :uuid .New (),
41
40
logger :logger ,
42
- stop :make (chan struct {},1 ),
43
41
}
44
42
}
45
43
@@ -86,8 +84,11 @@ func (lm *LatencyMeasurer) Measure(ctx context.Context, p Pubsub) LatencyMeasure
86
84
// MeasureAsync runs latency measurements asynchronously on a given interval.
87
85
// This function is expected to be run in a goroutine and will exit when the context is canceled.
88
86
func (lm * LatencyMeasurer )MeasureAsync (ctx context.Context ,p Pubsub ,interval time.Duration ) {
89
- lm .asyncTick = time .NewTicker (interval )
90
- defer lm .asyncTick .Stop ()
87
+ tick := time .NewTicker (interval )
88
+ defer tick .Stop ()
89
+
90
+ ctx ,cancel := context .WithCancelCause (ctx )
91
+ lm .asyncCancel = cancel
91
92
92
93
for {
93
94
// run immediately on first call, then sleep a tick before each invocation
@@ -101,14 +102,12 @@ func (lm *LatencyMeasurer) MeasureAsync(ctx context.Context, p Pubsub, interval
101
102
lm .last .Store (& measure )
102
103
103
104
select {
104
- case <- lm . asyncTick .C :
105
+ case <- tick .C :
105
106
continue
106
107
107
108
// bail out if signaled
108
- case <- lm .stop :
109
- return
110
109
case <- ctx .Done ():
111
- lm .logger .Debug (ctx ,"async measurementcontext canceled" ,slog .Error (ctx .Err ()))
110
+ lm .logger .Debug (ctx ,"async measurement canceled" ,slog .Error (ctx .Err ()))
112
111
return
113
112
}
114
113
}
@@ -130,11 +129,9 @@ func (lm *LatencyMeasurer) MeasurementCount() int64 {
130
129
131
130
// Stop stops any background measurements.
132
131
func (lm * LatencyMeasurer )Stop () {
133
- if lm .asyncTick = =nil {
134
- return
132
+ if lm .asyncCancel ! =nil {
133
+ lm . asyncCancel ( xerrors . New ( "stopped" ))
135
134
}
136
- lm .asyncTick .Stop ()
137
- lm .stop <- struct {}{}
138
135
}
139
136
140
137
func (lm * LatencyMeasurer )latencyChannelName ()string {