2
0

utils.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package utils
  2. import "time"
  3. // RetryStrategy specifies a strategy to retry an operation after waiting a while,
  4. // with hooks for successful and unsuccessful (>=max) tries.
  5. type RetryStrategy struct {
  6. Wait func(time.Duration)
  7. WaitTime time.Duration
  8. WaitTimeIncrease time.Duration
  9. MaxTries int
  10. Try func() error
  11. OnMaxTries func()
  12. OnSuccess func()
  13. }
  14. // DoStrategy does the retry strategy specified in the struct, waiting before retrying an operator,
  15. // up to a max number of tries, and if executes a success "finalizer" operation if a retry is successful
  16. func (rs RetryStrategy) DoStrategy() {
  17. err := rs.Try()
  18. if err == nil {
  19. rs.OnSuccess()
  20. return
  21. }
  22. tries := 1
  23. for {
  24. if tries >= rs.MaxTries {
  25. rs.OnMaxTries()
  26. return
  27. }
  28. rs.Wait(rs.WaitTime)
  29. if err := rs.Try(); err != nil {
  30. tries++ // we tried, increase count
  31. rs.WaitTime += rs.WaitTimeIncrease // for the next time, sleep more
  32. continue // retry
  33. }
  34. rs.OnSuccess()
  35. return
  36. }
  37. }