backoff.go 489 B

123456789101112131415161718192021222324252627282930313233343536
  1. package tftp
  2. import (
  3. "math/rand"
  4. "time"
  5. )
  6. const (
  7. defaultTimeout = 5 * time.Second
  8. defaultRetries = 5
  9. )
  10. type backoffFunc func(int) time.Duration
  11. type backoff struct {
  12. attempt int
  13. handler backoffFunc
  14. }
  15. func (b *backoff) reset() {
  16. b.attempt = 0
  17. }
  18. func (b *backoff) count() int {
  19. return b.attempt
  20. }
  21. func (b *backoff) backoff() {
  22. if b.handler == nil {
  23. time.Sleep(time.Duration(rand.Int63n(int64(time.Second))))
  24. } else {
  25. time.Sleep(b.handler(b.attempt))
  26. }
  27. b.attempt++
  28. }