github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/telemetry/ticker.go (about) 1 package telemetry 2 3 import ( 4 "math/rand" 5 "time" 6 ) 7 8 const ( 9 jitterUpperBound = 60 // s 10 ) 11 12 // ticker represents a ticker interface that 13 // can be mocked for more reliable tests. 14 type ticker interface { 15 C() <-chan time.Time 16 Stop() 17 } 18 19 func newStdTicker(d time.Duration) *stdTicker { 20 return &stdTicker{ 21 Ticker: time.NewTicker(withJitter(d)), 22 } 23 } 24 25 // stdTicker is a wrapper around the standard 26 // library time ticker. 27 type stdTicker struct { 28 *time.Ticker 29 } 30 31 func (t *stdTicker) C() <-chan time.Time { 32 return t.Ticker.C 33 } 34 35 func (t *stdTicker) Stop() { 36 t.Ticker.Stop() 37 } 38 39 // withJitter sums a random jitter of [0, 59)s to the given duration. 40 // This will randomize the tenant pushers push time to avoid many overlapping 41 // requests to the API and instead distribute them more evenly. 42 func withJitter(d time.Duration) time.Duration { 43 jitter := time.Duration(rand.Intn(jitterUpperBound)) * time.Second 44 return d + jitter 45 }