Documentation ¶
Overview ¶
Package jitter provides functionality for generating durations and tickers that deviate from true periodicity within specified bounds.
All functionality in this package currently utilizes global rand, so you will want to seed it before utilization.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Scale ¶
Scale simulates jitter by scaling a time.Duration randomly within factor f.
The duration d must be greater than zero; and the scaling factor f must be within the range 0 < f <= 1.0, or Scale will panic.
Example ¶
package main import ( "fmt" "math/rand" "time" "github.com/mroth/jitter" ) func main() { rand.Seed(1) for i := 0; i < 5; i++ { fmt.Println(jitter.Scale(time.Second, 0.5)) } }
Output: 1.44777941s 582.153551ms 1.166145821s 735.010051ms 787.113937ms
Types ¶
type Ticker ¶
type Ticker struct { C <-chan time.Time // The channel on which the ticks are delivered. // contains filtered or unexported fields }
A Ticker holds a channel that delivers `ticks' of a clock at intervals, deviating with constrained random jitter.
It adjusts the intervals or drops ticks to make up for slow receivers.
func NewTicker ¶
NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument, but adjusted with random jitter based on the specified scaling factor.
The duration d must be greater than zero; and the scaling factor f must be within the range 0 < f <= 1.0, or NewTicker will panic.
Stop the ticker to release associated resources.
Example ¶
package main import ( "fmt" "math/rand" "time" "github.com/mroth/jitter" ) func main() { // jitter uses the global random source, seed it appropriately. for this // example, we seed it to a constant for predictable output. rand.Seed(42) // ticker with base duration of 10 milliseconds and 0.5 scaling factor ticker := jitter.NewTicker(10*time.Millisecond, 0.5) defer ticker.Stop() prev := time.Now() for i := 0; i < 5; i++ { t := <-ticker.C // time elapsed is random in range (5ms, 15ms). fmt.Println("Time elapsed since last tick: ", t.Sub(prev)) prev = t } }
Output:
func NewTickerWithContext ¶
NewTickerWithContext is identical to NewTicker but also takes a specified context. If this context is cancelled, the Ticker will automatically Stop.