-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchain.go
68 lines (58 loc) · 1.41 KB
/
chain.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
package cronjob
import (
"time"
)
// Chain is a slice of decorator functions.
type Chain []func(FuncJob) FuncJob
// NewChain returns a chain of decorators which run in FIFO order.
func NewChain(c ...func(FuncJob) FuncJob) Chain {
return Chain(c)
}
// MergeChains merges n (field) chains into 1 parent chain.
func MergeChains(n ...Chain) (merged Chain) {
for _, chain := range n {
merged = append(merged, chain...)
}
return
}
// Run runs job (field) with the chains.
func (c Chain) Run(job FuncJob) {
// decorate job.
for i := range c {
job = c[len(c)-i-1](job)
}
// run decorated job.
job()
}
// Retry will retry your job decorated with past chains max (field) times with a timeout (field)
// delay.
//
// Retry MUST only be added first in cronjob.NewChain() if you want all the chains to run properly.
// Not adding retry as the first argument in NewChain will cause unexpected behaviour.
func Retry(timeout time.Duration, max int) func(FuncJob) FuncJob {
if max <= 0 {
max = 1
}
if timeout < time.Second {
timeout = time.Second
}
return func(fj FuncJob) FuncJob {
// call chain from here.
err := fj()
if err != nil {
ticker := time.NewTicker(timeout)
defer ticker.Stop()
// use 1 to compensate for first error checking call.
for i := 1; i < max; i++ {
<-ticker.C
if err := fj(); err == nil {
break
}
}
}
// ends chain.
return func() error {
return nil
}
}
}