This repository has been archived by the owner on May 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
retry.go
56 lines (51 loc) · 1.31 KB
/
retry.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
45
46
47
48
49
50
51
52
53
54
55
56
// Package retry helps retrying functions in Go, certain number of times or
// infinitely - Also can be used as a schaduler.
package retry
import (
"time"
)
type recovered struct {
e interface{}
}
func (r *recovered) Error() string { return "RECOVERED, UNKNOWN ERROR; CALL CausedBy() interface{}" }
func (r *recovered) CausedBy() interface{} { return r.e }
// Try tries to run a function and recovers from a panic, in case
// one happens, and returns the error, if there are any.
func Try(f func() error) (errRun error) {
defer func() {
if e := recover(); e != nil {
errRun = &recovered{e: e}
}
}()
return f()
}
// Retry retries running a function, numberOfRetries times.
// If numberOfRetries < 0, it runs it forever as long as there are
// any errors. If there are no errors, it will return. If
// numberOfRetries > 1, it will sleep between two attemps,
// the default period is 5 seconds.
func Retry(
f func() error,
numberOfRetries int,
onError func(error),
period ...time.Duration) {
p := time.Second * 5
if len(period) > 0 && period[0] > 0 {
p = period[0]
}
for numberOfRetries != 0 {
if numberOfRetries > 0 {
numberOfRetries--
}
if err := Try(f); err != nil {
if onError != nil {
onError(err)
}
if numberOfRetries != 0 {
time.Sleep(p)
}
} else {
break
}
}
}