-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.go
111 lines (91 loc) · 1.97 KB
/
tasks.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package golaze
import (
"context"
"sync"
"time"
"github.com/rs/zerolog/log"
)
type TaskConfig struct {
Name string
Exec func(state *State, cancel chan bool) error
MaxRetries int
RetryInterval time.Duration
Repeat int // -1 for infinite, 0 for no repeat, > 0 for n times
RepeatDelay time.Duration
Timeout time.Duration
RunHistory []time.Time
Cancel chan bool
Done chan bool
lock sync.Mutex
}
type Task struct {
*TaskConfig
}
func NewTask(config *TaskConfig) *Task {
if config.Cancel == nil {
config.Cancel = make(chan bool)
}
if config.Exec == nil {
config.Exec = func(state *State, cancel chan bool) error {
return nil
}
}
if config.Done == nil {
config.Done = make(chan bool)
}
if config.Timeout == 0 {
config.Timeout = 5 * time.Second
}
if config.RetryInterval == 0 {
config.RetryInterval = 5 * time.Second
}
if config.RepeatDelay == 0 {
config.RepeatDelay = 1 * time.Second
}
return &Task{
config,
}
}
func (t *Task) Run(ctx context.Context, state *State) {
taskError := make(chan error)
go func() {
go func() {
t.lock.Lock()
t.RunHistory = append(t.RunHistory, time.Now())
t.lock.Unlock()
log.Info().Msgf("task %s started", t.Name)
err := t.Exec(state, t.Cancel)
taskError <- err
}()
select {
case <-ctx.Done():
log.Info().Msgf("task %s stopped", t.Name)
case <-t.Cancel:
log.Info().Msgf("task %s cancelled", t.Name)
case err := <-taskError:
if err != nil {
log.Error().Err(err).Msgf("task %s failed", t.Name)
} else {
log.Info().Msgf("task %s completed", t.Name)
}
case <-time.After(t.Timeout):
log.Error().Msgf("task %s timed out", t.Name)
}
t.Done <- true
}()
<-t.Done
if taskError != nil && t.MaxRetries > 0 {
t.MaxRetries--
time.Sleep(t.RetryInterval)
t.Run(ctx, state)
}
if t.Repeat > 0 {
t.Repeat--
time.Sleep(t.RepeatDelay)
t.Run(ctx, state)
}
if t.Repeat == -1 {
time.Sleep(t.RepeatDelay)
t.Run(ctx, state)
}
}