-
Notifications
You must be signed in to change notification settings - Fork 10
/
misc.go
83 lines (73 loc) · 1.71 KB
/
misc.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package util
import (
"context"
"sync"
"time"
"github.com/zhiqiangxu/util/logger"
"go.uber.org/zap"
)
// GoFunc runs a goroutine under WaitGroup
func GoFunc(routinesGroup *sync.WaitGroup, f func()) {
routinesGroup.Add(1)
go func() {
defer routinesGroup.Done()
f()
}()
}
// TryUntilSuccess will try f until success
func TryUntilSuccess(f func() bool, duration time.Duration) {
var r bool
for {
r = f()
if r {
return
}
time.Sleep(duration)
}
}
// RunWithRecovery for run exec, calls recoverFn when panic
func RunWithRecovery(exec func(), recoverFn func(r interface{})) {
defer func() {
r := recover()
if r != nil {
logger.Instance().Error("panic in the recoverable goroutine",
zap.Reflect("r", r),
zap.Stack("stack trace"))
if recoverFn != nil {
recoverFn(r)
}
}
}()
exec()
}
// RunWithRetry will run the f with backoff and retry.
// retryCnt: Max retry count
// backoff: When run f failed, it will sleep backoff * triedCount time.Millisecond.
// Function f should have two return value. The first one is an bool which indicate if the err if retryable.
// The second is if the f meet any error.
func RunWithRetry(retryCnt int, backoff uint64, f func() (bool, error)) (err error) {
var retryAble bool
for i := 1; i <= retryCnt; i++ {
retryAble, err = f()
if err == nil || !retryAble {
return
}
sleepTime := time.Duration(backoff*uint64(i)) * time.Millisecond
time.Sleep(sleepTime)
}
return
}
// RunWithCancel for run a job with cancel-ability
func RunWithCancel(ctx context.Context, f, cancel func()) {
var wg sync.WaitGroup
doneCh := make(chan struct{})
GoFunc(&wg, func() {
f()
close(doneCh)
})
select {
case <-ctx.Done():
cancel()
case <-doneCh:
}
}