Documentation
¶
Overview ¶
Package timetool provides tools and utilities for dealing with that most precious of commodities: time.
Index ¶
- Constants
- Variables
- func FromMillis(millis int64) time.Timedeprecated
- func RetryWithBackoff(ctx context.Context, iters int, retry RetryFunc) errordeprecated
- func RetryWithBackoffDuration(dur time.Duration, iters int, retry RetryFunc) error
- func Sleep(ctx context.Context, d time.Duration) error
- func SleepUntil(ctx context.Context, t time.Time) error
- func ToMillis(t time.Time) int64deprecated
- type Backoff
- func (b Backoff) MustTotalDelay(d time.Duration) *Backoff
- func (b *Backoff) Retry(ctx context.Context, retry RetryFunc) error
- func (b Backoff) WithInitialWait(d time.Duration) *Backoff
- func (b Backoff) WithStartWait(d time.Duration) *Backoff
- func (b Backoff) WithTotalDelay(d time.Duration) (*Backoff, error)
- type Error
- type NormalTicker
- type RetryFunc
Constants ¶
const ErrBadJitter = Error("invalid jitter value; must be [0.0, 100.0)")
ErrBadJitter is returned when an invalid jitter value has been requested.
const ErrMissingDeadline = Error("context must have a deadline")
ErrMissingDeadline is returned by functions expecting a Deadline but are passed a Context devoid of such nature.
const ErrNegativeDelay = Error("negative delay value; time travel not yet supported")
ErrNegativeDelay is returned when an applicable time.Duration value is negative.
const ErrNilReceiver = Error("nil reciver")
ErrNilReceiver is returned when a method is called using a nil pointer reciever.
const ErrRetriesExhausted = Error("all retries exhausted")
ErrRetriesExhausted is returned by RetryWithBackoff if all retry attempts have been unsuccessful.
const ErrTickerActive = Error("ticker is active")
ErrTickerActive is returned by NormalTicker's Err method if the ticker is still active (i.e. it has not been stopped).
const ErrTimeWarp = Error("valid context has deadline in the past")
ErrTimeWarp is returned by RetryWithBackoff in the freakishly uncommon event that a context ends up with a deadline in the past and a Done channel that does not return.
const ErrTooFewIterations = Error("number of iterations must be at least 2")
ErrTooFewIterations is returned if the number of requested iterations is less than 2.
const ErrZeroCoefficient = Error("coefficient cannot be zero")
ErrZeroCoefficient is returned when a Backoff.Coefficient value is zero.
Variables ¶
var StdBackoff = &Backoff{Iterations: 5, Coefficient: time.Second, Jitter: 0.1}
StdBackoff provides a Backoff with common parameters.
Functions ¶
func FromMillis
deprecated
func RetryWithBackoff
deprecated
RetryWithBackoff calls the given RetryFunc a maximum of iters times until it returns true. The provided context must have a defined deadline and the number of iterations requested must be at least 2. Nil is returned if retry returns true before the deadline expires and within the stated number of iterations.
Note that, even if retry returns true, the deadline is checked a final time and, if it has expired, ctx.Err() is returned.
If the provided Context has no defined deadline, ErrMissingDeadline is returned. ErrTooFewIterations will be returned if iters is less than 2. If each call to retry returns false, ErrRetriesExhausted is returned.
Deprecated: Please use *Backoff.Retry instead.
func RetryWithBackoffDuration ¶
RetryWithBackoffDuration is a wrapper around RetryWithBackoff accepting a Duration in leu of a Context.
func Sleep ¶
Sleep is a wrapper around time.Sleep that may be interrupted by the cancellation of a Context. Sleep returns ctx.Err() if cancelled by the Context, otherwise it returns nil.
func SleepUntil ¶
SleepUntil is a wrapper around Sleep that accepts a time.Time instead of a time.Duration.
Types ¶
type Backoff ¶ added in v1.3.0
type Backoff struct {
// Iterations declares the maximum number execution attempts.
Iterations int
// Coefficient indicates the initial delay between attempts.
Coefficient time.Duration
// Jitter is a random modifier percentage applied to each delay period.
Jitter float64
// contains filtered or unexported fields
}
Backoff defines the parameters for a set of retries with exponential backoff.
func CalculateBackoff ¶ added in v1.5.0
CalculateBackoff returns a new Backoff having a Coefficient value calculated for the given number of iterations and desired total delay time.
If a non-zero jitter value is provided, it will be included in the return value but it will not be used to calculate the resulting Coefficient.
An error is returned if iters < 2, total < 0, or jitter is outside [0, 100).
func MustCalculateBackoff ¶ added in v1.5.0
MustCalculateBackoff is a wrapper around CalculateBackoff that will panic if an error is returned.
func (Backoff) MustTotalDelay ¶ added in v1.5.0
MustTotalDelay is a wrapper around WithTotalDelay that will panic if an error is returned.
func (*Backoff) Retry ¶ added in v1.3.0
Retry calls the given RetryFunc up to b.Iterations times until it returns true or the provided Context is cancelled, whichever comes first.
If the initial call to RetryFunc returns false (indicating it should be reattempted), the RetryFunc is (by default) rerun immediately. Subsequent execution attempts (after the first) are interleaved with an exponentially increasing delay based on the receiver such that each delay is calculated as:
multiple = 2 ** (attempt_num - 1) ± random_jitter delay = b.Coefficient * multiple
...and, when the reciever's Jitter field is non-zero, 'random_jitter' is defined as:
random = rand.Float64() // A value in the half-open interval [0.0,1.0) jitter = (b.Jitter * random) - (b.Jitter / 2) / 100
...or, rather... plus or minus jitter-percent over two.
If the receiver declares fewer than 2 iterations an error will be returned.
The receiver's delay Coefficient must be a positive, non-zero value or an error will be returned.
If b.Jitter is 0, no Jitter will be applied. Otherwise, the Jitter value must be in the range (0,100) or an error will be returned.
func (Backoff) WithInitialWait ¶ added in v1.5.0
WithInitialWait returns a pointer to its receiver and adds an "initial wait time" to Retry execution, after a failed first attempt.
Normally, when a RetryFunc does not succeed on its first attempt, the next attempt is executed immediately without delay. Adding this "initial wait time" will inject an additional (static) delay in this situation.
No other inter-attempt delays are effected by this value; those delays will continue to be calculated using the current iteration number and the reciever's Coefficient and Jitter fields.
If the Context provided to Retry becomes done during this initial wait time, Retry will immediately return ctx.Err() without executing its next attempt.
func (Backoff) WithStartWait ¶ added in v1.5.0
WithStartWait returns a pointer to its receiver that adds a "startup wait time" to Retry execution (for those situations where you're quite certain the RetryFunc will not succeed right away).
Normally, the Retry method will execute its first attempt immediately. However, with a defined "startup wait time", Retry will Sleep for the given duration before executing its first attempt.
If the Context provided to Retry becomes done during this startup wait time, Retry will immediately return ctx.Err() without executing any attempts.
func (Backoff) WithTotalDelay ¶ added in v1.5.0
WithTotalDelay returns a pointer to its receiver with a new Coefficient value calculated to consume the provided Duration based on the receiver's other field values.
This is similar to the CalculateBackoff function but also considers the optional "startup wait time" and/or "initial wait time" (if any) when calculating a new Coefficient value.
A Coefficient value will only be calculated if the receiver's Iterations field is greater than 2 -- since a call to Retry with only 2 iterations never refers to the Coefficient field. However, if Iterations is exactly 2, this method has the same effect as calling WithInitialWait.
On error, a nil pointer will always be returned.
ErrNegativeDelay is retured if the resultant total delay time, after any "startup wait time" and/or "initial wait time" values are considered, is calculated to be a negative value.
If the receiver's Iterations field is less than 2, ErrTooFewIterations is returned.
type NormalTicker ¶ added in v1.4.0
Type NormalTicker holds a channel that delivers "ticks" of a clock over a normally distributed time interval.
func NewNormalTicker ¶ added in v1.4.0
func NewNormalTicker(ctx context.Context, mean, stddev time.Duration) *NormalTicker
NewNormalTicker returns a new NormalTicker containing a channel that will send the current time on the channel after each tick. The period of the ticks is over a normal distribution as specified by the mean and stddev arguments. The ticker will drop ticks to make up for slow receivers and will continue to send values to its channel until the Stop method is called or the given context is expired.
func (*NormalTicker) Err ¶ added in v1.4.0
func (nt *NormalTicker) Err() error
Err returns an error indicating how the ticker was stopped. If the Stop method was called, a nil error returned. If the constructor's Context has expired, ctx.Err() is returned. If the ticker has not been stopped, ErrTickerActive is returned.
func (*NormalTicker) Stop ¶ added in v1.4.0
func (nt *NormalTicker) Stop()
Stop turns off the ticker. After Stop, no more ticks will be sent. Stop does not close the channel, to prevent a concurrent goroutine reading from the channel from seeing an erroneous "tick". If Stop is called before the constructor's Context has expired, the Err method will return a nil error.
type RetryFunc ¶
RetryFunc is the function provided to a retry operation that should be executed until it succeeds, as indicated by its return value. i.e. If the function returns false, it will be retried after a brief delay.
The function will be passed a single int argument indicating the current (zero based) iteration number.