github.com/jxskiss/gopkg@v0.17.3/retry/backoff.go (about)

     1  package retry
     2  
     3  import (
     4  	"math/rand"
     5  	"time"
     6  )
     7  
     8  // AddJitter adds random jitter to the duration.
     9  //
    10  // This adds or subtracts time from the duration within a given jitter fraction.
    11  // For example for 10s and jitter 0.1, it will return a time within [9s, 11s])
    12  func AddJitter(duration time.Duration, jitter float64) time.Duration {
    13  	multiplier := jitter * (rand.Float64()*2 - 1)
    14  	return time.Duration(float64(duration) * (1 + multiplier))
    15  }
    16  
    17  // Backoff doubles the given duration. If max is given larger than 0, and
    18  // the doubled value is greater than max, it will be limited to max. The
    19  // param jitter can be used to add random jitter to the doubled duration.
    20  func Backoff(duration, max time.Duration, jitter float64) (double, withJitter time.Duration) {
    21  	double = duration * 2
    22  	if max > 0 && double > max {
    23  		double = max
    24  	}
    25  	withJitter = AddJitter(double, jitter)
    26  	return
    27  }
    28  
    29  type strategy func(time.Duration) time.Duration
    30  
    31  func exp(sleep time.Duration) time.Duration {
    32  	return sleep * 2
    33  }
    34  
    35  func constant(sleep time.Duration) time.Duration {
    36  	return sleep
    37  }
    38  
    39  type linear struct {
    40  	step time.Duration
    41  }
    42  
    43  func (l linear) next(sleep time.Duration) time.Duration {
    44  	return sleep + l.step
    45  }