-
Notifications
You must be signed in to change notification settings - Fork 0
/
re.go
44 lines (35 loc) · 760 Bytes
/
re.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package re
import (
"errors"
"time"
)
// Try, at first, executes given task with no timer started.
// If an error occurs, it starts a Ticker and a Timer and executes
// the task every time Ticker ticks unless Timer is finish.
// If Timer finishes, Try returns the latest error returned from the task.
func Try(task func() error, period, timeout time.Duration) error {
if task == nil {
return errors.New("task is nil")
}
if err := task(); err == nil {
return nil
}
ticker := time.NewTicker(period)
timer := time.NewTimer(timeout)
defer func() {
ticker.Stop()
timer.Stop()
}()
var err error
for {
select {
case <-ticker.C:
if err = task(); err != nil {
continue
}
return nil
case <-timer.C:
return err
}
}
}