-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
52 lines (44 loc) · 1.05 KB
/
task.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
package art
import (
"errors"
"time"
"github.com/cenkalti/backoff/v4"
)
func ReliableTask(task func() error, allowStop func() bool, retryMaxSecond int, fixup func() error) error {
if task == nil || allowStop == nil {
panic("ReliableTask: task or allowStop is nil")
}
if retryMaxSecond == 0 {
const RetryUntilAllowStop = 0
retryMaxSecond = RetryUntilAllowStop
}
param := backoff.NewExponentialBackOff()
param.InitialInterval = 10 * time.Second
param.RandomizationFactor = 0.5
param.Multiplier = 1.5
param.MaxInterval = 1 * time.Minute
param.MaxElapsedTime = time.Duration(retryMaxSecond) * time.Second
Task:
err := task()
if err == nil {
return nil
}
if fixup == nil {
return backoff.Retry(func() error {
if allowStop() {
return backoff.Permanent(errors.New("task has actively been stopped"))
}
return task()
}, param)
}
err = backoff.Retry(func() error {
if allowStop() {
return backoff.Permanent(errors.New("task has actively been stopped"))
}
return fixup()
}, param)
if err == nil {
goto Task
}
return err
}