retry.go 408 B

1234567891011121314151617181920212223242526
  1. package model
  2. import (
  3. "time"
  4. )
  5. // Retry is
  6. func Retry(attempts int, sleep time.Duration, fn func() error) error {
  7. if err := fn(); err != nil {
  8. if s, ok := err.(stop); ok {
  9. // Return the original error for later checking
  10. return s.error
  11. }
  12. if attempts--; attempts > 0 {
  13. time.Sleep(sleep)
  14. return Retry(attempts, 2*sleep, fn)
  15. }
  16. return err
  17. }
  18. return nil
  19. }
  20. type stop struct {
  21. error
  22. }