constant.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package backoff
  2. import (
  3. "context"
  4. "time"
  5. )
  6. type ConstantInterval struct {
  7. interval time.Duration
  8. jitter jitter
  9. }
  10. func NewConstantInterval(options ...ConstantOption) *ConstantInterval {
  11. jitterFactor := 0.0
  12. interval := time.Minute
  13. var rng Random
  14. for _, option := range options {
  15. switch option.Ident() {
  16. case identInterval{}:
  17. interval = option.Value().(time.Duration)
  18. case identJitterFactor{}:
  19. jitterFactor = option.Value().(float64)
  20. case identRNG{}:
  21. rng = option.Value().(Random)
  22. }
  23. }
  24. return &ConstantInterval{
  25. interval: interval,
  26. jitter: newJitter(jitterFactor, rng),
  27. }
  28. }
  29. func (g *ConstantInterval) Next() time.Duration {
  30. return time.Duration(g.jitter.apply(float64(g.interval)))
  31. }
  32. type ConstantPolicy struct {
  33. cOptions []ControllerOption
  34. igOptions []ConstantOption
  35. }
  36. func NewConstantPolicy(options ...Option) *ConstantPolicy {
  37. var cOptions []ControllerOption
  38. var igOptions []ConstantOption
  39. for _, option := range options {
  40. switch opt := option.(type) {
  41. case ControllerOption:
  42. cOptions = append(cOptions, opt)
  43. default:
  44. igOptions = append(igOptions, opt.(ConstantOption))
  45. }
  46. }
  47. return &ConstantPolicy{
  48. cOptions: cOptions,
  49. igOptions: igOptions,
  50. }
  51. }
  52. func (p *ConstantPolicy) Start(ctx context.Context) Controller {
  53. ig := NewConstantInterval(p.igOptions...)
  54. return newController(ctx, ig, p.cOptions...)
  55. }