github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/utils/retry.go (about)

     1  package utils
     2  
     3  import "time"
     4  
     5  // RetryWithExpBackoff can be used to call several times a function until it
     6  // returns no error or the maximum count of calls has been reached. Between two
     7  // calls, it will wait, first by the given delay, and after that, the delay
     8  // will double after each failure.
     9  func RetryWithExpBackoff(count int, delay time.Duration, fn func() error) error {
    10  	err := fn()
    11  	if err == nil {
    12  		return nil
    13  	}
    14  	for i := 1; i < count; i++ {
    15  		time.Sleep(delay)
    16  		delay *= 2
    17  		err = fn()
    18  		if err == nil {
    19  			return nil
    20  		}
    21  	}
    22  	return err
    23  }