github.com/Cloud-Foundations/Dominator@v0.3.4/lib/retry/impl.go (about)

     1  package retry
     2  
     3  import (
     4  	"errors"
     5  	"time"
     6  
     7  	"github.com/Cloud-Foundations/Dominator/lib/backoffdelay"
     8  )
     9  
    10  var defaultSleeper = &simpleSleeper{}
    11  
    12  type simpleSleeper struct{}
    13  
    14  func retry(fn func() bool, params Params) error {
    15  	params.prepare()
    16  	stopTime := time.Now().Add(params.RetryTimeout)
    17  	var tryCount uint64
    18  	for {
    19  		tryCount++
    20  		if fn() {
    21  			return nil
    22  		}
    23  		if params.RetryTimeout > 0 && time.Since(stopTime) >= 0 {
    24  			return errors.New("timed out")
    25  		}
    26  		if params.MaxRetries > 0 && tryCount >= params.MaxRetries {
    27  			return errors.New("too many retries")
    28  		}
    29  		params.Sleeper.Sleep()
    30  	}
    31  }
    32  
    33  func (p *Params) prepare() {
    34  	if p.Sleeper == nil {
    35  		p.Sleeper = defaultSleeper
    36  	} else if resetter, ok := p.Sleeper.(backoffdelay.Resetter); ok {
    37  		resetter.Reset()
    38  	}
    39  }
    40  
    41  func (s *simpleSleeper) Sleep() {
    42  	time.Sleep(100 * time.Millisecond)
    43  }