mirror of
https://github.com/luscis/openlan.git
synced 2025-10-05 16:47:11 +08:00
42 lines
661 B
Go
Executable File
42 lines
661 B
Go
Executable File
package libol
|
|
|
|
import "time"
|
|
|
|
type Promise struct {
|
|
Count int
|
|
MaxTry int
|
|
First time.Duration // the delay time.
|
|
MinInt time.Duration // the normal time.
|
|
MaxInt time.Duration // the max delay time.
|
|
}
|
|
|
|
func NewPromise() *Promise {
|
|
return &Promise{
|
|
First: time.Second * 2,
|
|
MaxInt: time.Minute,
|
|
MinInt: time.Second * 10,
|
|
}
|
|
}
|
|
|
|
func (p *Promise) Done(call func() error) {
|
|
for {
|
|
p.Count++
|
|
if p.MaxTry > 0 && p.Count > p.MaxTry {
|
|
return
|
|
}
|
|
if err := call(); err == nil {
|
|
return
|
|
}
|
|
time.Sleep(p.First)
|
|
if p.First < p.MaxInt {
|
|
p.First += p.MinInt
|
|
}
|
|
}
|
|
}
|
|
|
|
func (p *Promise) Go(call func() error) {
|
|
Go(func() {
|
|
p.Done(call)
|
|
})
|
|
}
|