-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |