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.
Note that using a factor of math.Abs(f) > 1.0 may result in the sign of the result changing (e.g. a positive Duration may become negative, and vice versa). Additionally, a factor of math.Abs(f) == 1.0 may result in a zero Duration. If you wish to avoid these potential scenarios, confine your factor such that 0.0 < math.Abs(f) < 1.0.
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"
"time"
"github.com/mroth/jitter"
)
func main() {
// ticker with base duration of 1 second and 0.5 scaling factor
ticker := jitter.NewTicker(time.Second, 0.5)
defer ticker.Stop()
prev := time.Now()
for i := 0; i < 10; i++ {
t := <-ticker.C // time elapsed random in range [0.5s, 1.5s]
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.