Skip to content

Commit

Permalink
pkg/services: add Ticker
Browse files Browse the repository at this point in the history
  • Loading branch information
jmank88 committed Jan 12, 2024
1 parent 237f56d commit ac6a101
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions pkg/services/ticker.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package services

import (
"time"

"github.com/smartcontractkit/chainlink-common/pkg/utils"
)

// Ticker is like time.Ticker, but with two differences:
// - the first tick is fired immediately
// - each period has jitter applied by utils.WithJitter.
type Ticker struct {
C <-chan time.Time
stop StopChan
}

func (t *Ticker) Stop() { close(t.stop) }

// NewTicker returns a new Ticker with a period of d.
func NewTicker(d time.Duration) *Ticker {
c := make(chan time.Time) // unbuffered so we block and delay if not being handled
t := Ticker{C: c, stop: make(StopChan)}
go func() {
c <- time.Now()
for {
select {
case <-t.stop:
return

case <-time.After(utils.WithJitter(d)):
select {
case <-t.stop:
return
case c <- time.Now():
}
}
}
}()
return &t
}

0 comments on commit ac6a101

Please sign in to comment.