-
Notifications
You must be signed in to change notification settings - Fork 0
/
tasks.go
88 lines (70 loc) · 1.46 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
package golaze
import (
"time"
"github.com/rs/zerolog/log"
)
type TaskConfig struct {
Name string
Exec func(state *State) 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
Done chan bool
}
type Task struct {
*TaskConfig
}
func NewTask(config *TaskConfig) *Task {
if config.Exec == nil {
config.Exec = func(state *State) 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
}
if config.Repeat == 0 {
config.Repeat = 1
}
return &Task{
config,
}
}
func (t *Task) IsRunning() bool {
// Check if the task is currently running
// by checking the length of the Done channel
select {
case <-t.Done:
return false
default:
return true
}
}
func (t *Task) Run(state *State) {
go func() {
t.RunHistory = append(t.RunHistory, time.Now())
if err := t.Exec(state); err != nil {
log.Error().Err(err).Msgf("task %s failed", t.Name)
}
t.Done <- true
}()
select {
case <-t.Done:
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
}
}