| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"time" |
| 5 |
) |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
type AttemptStrategy struct { |
| 13 |
Total time.Duration |
| 14 |
Delay time.Duration |
| 15 |
Min int |
| 16 |
} |
| 17 |
|
| 18 |
type Attempt struct { |
| 19 |
strategy AttemptStrategy |
| 20 |
last time.Time |
| 21 |
end time.Time |
| 22 |
force bool |
| 23 |
count int |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
func (s AttemptStrategy) Start() *Attempt { |
| 28 |
now := time.Now() |
| 29 |
return &Attempt{ |
| 30 |
strategy: s, |
| 31 |
last: now, |
| 32 |
end: now.Add(s.Total), |
| 33 |
force: true, |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
func (a *Attempt) Next() bool { |
| 40 |
now := time.Now() |
| 41 |
sleep := a.nextSleep(now) |
| 42 |
if !a.force && !now.Add(sleep).Before(a.end) && a.strategy.Min <= a.count { |
| 43 |
return false |
| 44 |
} |
| 45 |
a.force = false |
| 46 |
if sleep > 0 && a.count > 0 { |
| 47 |
time.Sleep(sleep) |
| 48 |
now = time.Now() |
| 49 |
} |
| 50 |
a.count++ |
| 51 |
a.last = now |
| 52 |
return true |
| 53 |
} |
| 54 |
|
| 55 |
func (a *Attempt) nextSleep(now time.Time) time.Duration { |
| 56 |
sleep := a.strategy.Delay - now.Sub(a.last) |
| 57 |
if sleep < 0 { |
| 58 |
return 0 |
| 59 |
} |
| 60 |
return sleep |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
func (a *Attempt) HasNext() bool { |
| 67 |
if a.force || a.strategy.Min > a.count { |
| 68 |
return true |
| 69 |
} |
| 70 |
now := time.Now() |
| 71 |
if now.Add(a.nextSleep(now)).Before(a.end) { |
| 72 |
a.force = true |
| 73 |
return true |
| 74 |
} |
| 75 |
return false |
| 76 |
} |