Refactor periodicallySendMonitoringData

in order to return directly when the context is done and not just at the next iteration.
This commit is contained in:
Maximilian Paß
2023-09-04 10:44:33 +02:00
parent a01bd0fa7e
commit b28b87d56f
2 changed files with 13 additions and 7 deletions

View File

@ -173,9 +173,13 @@ func (s *localStorage[T]) sendMonitoringData(id string, o T, eventType EventType
} }
func (s *localStorage[T]) periodicallySendMonitoringData(d time.Duration, ctx context.Context) { func (s *localStorage[T]) periodicallySendMonitoringData(d time.Duration, ctx context.Context) {
for ctx.Err() == nil { for {
stub := new(T) select {
s.sendMonitoringData("", *stub, Periodically, s.Length()) case <-ctx.Done():
<-time.After(d) return
case <-time.After(d):
stub := new(T)
s.sendMonitoringData("", *stub, Periodically, s.Length())
}
} }
} }

View File

@ -181,10 +181,12 @@ func TestNewMonitoredLocalStorage_Periodically(t *testing.T) {
NewMonitoredLocalStorage[string]("testMeasurement", func(p *write.Point, o string, eventType EventType) { NewMonitoredLocalStorage[string]("testMeasurement", func(p *write.Point, o string, eventType EventType) {
callbackCalls++ callbackCalls++
assert.Equal(t, Periodically, eventType) assert.Equal(t, Periodically, eventType)
}, 200*time.Millisecond, ctx) }, 2*tests.ShortTimeout, ctx)
time.Sleep(tests.ShortTimeout) <-time.After(tests.ShortTimeout)
assert.Equal(t, 0, callbackCalls)
<-time.After(2 * tests.ShortTimeout)
assert.Equal(t, 1, callbackCalls) assert.Equal(t, 1, callbackCalls)
time.Sleep(200 * time.Millisecond) <-time.After(2 * tests.ShortTimeout)
assert.Equal(t, 2, callbackCalls) assert.Equal(t, 2, callbackCalls)
} }