github.com/simpleiot/simpleiot@v0.18.3/client/backoff.go (about)

     1  package client
     2  
     3  import (
     4  	"math"
     5  	"math/rand"
     6  	"time"
     7  )
     8  
     9  // ExpBackoff calculates an exponential time backup to max duration + a random fraction of 1s
    10  func ExpBackoff(attempts int, max time.Duration) time.Duration {
    11  	delay := max
    12  
    13  	// if attempts is too large, then things soon start to overflow
    14  	// so only calculate when # of attempts is relatively small
    15  	if attempts < 30 {
    16  		calc := time.Duration(math.Exp2(float64(attempts))) * time.Second
    17  		// if math.Exp2(..) is +Inf, then converting that to duration
    18  		// ends up being zero. If attempts is large, then duration may
    19  		// be negative -- should be covered by attempts > 50 above.
    20  		if calc > 0 && calc < max {
    21  			delay = calc
    22  		}
    23  	}
    24  
    25  	// randomize a bit
    26  	delay = delay + time.Duration(rand.Float32()*1000)*time.Millisecond
    27  	return delay
    28  }