github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/utils/timeutil/math.go (about) 1 package timeutil 2 3 import ( 4 "time" 5 6 "github.com/jxskiss/gopkg/v2/internal" 7 ) 8 9 // AddJitter adds random jitter to a duration. 10 // 11 // It adds or subtracts time from the duration within a given jitter fraction. 12 // For example for 10s and jitter 0.1, it returns a duration within [9s, 11s). 13 func AddJitter(duration time.Duration, jitter float64) time.Duration { 14 return internal.AddJitter(duration, jitter) 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_. 19 // The 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 }