-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
163 lines (136 loc) · 3.36 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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
package crony
import (
"errors"
"fmt"
"reflect"
"sync"
"time"
)
// Task structure describing a task to execute
// by a Crony
type Task struct {
sync.Mutex
fun interface{}
args []interface{}
nextRun time.Time
lastRun time.Time
tick time.Duration
running bool
async bool
Name string
}
var (
ErrTaskNotFunc = errors.New("not a function")
ErrTaskWrongNumOfArg = errors.New("wrong number of arguments")
ErrTaskWrongArgType = errors.New("wrong argument type")
)
// NewTask creates a new Task with a name
func NewTask(name string) *Task {
return &Task{Name: name}
}
// NewAsyncTask creates a new asynchronous Task with a name.
// An asynchronous task will run in a separate go routine and
// will de facto not be blocking
func NewAsyncTask(name string) *Task {
return NewTask(name).Async()
}
func (t *Task) control() error {
v := reflect.ValueOf(t.fun)
ft := reflect.TypeOf(t.fun)
if v.Kind() != reflect.Func {
return fmt.Errorf("%w %T", ErrTaskNotFunc, t.fun)
}
if ft.NumIn() != len(t.args) {
return fmt.Errorf("%w got %d expecting %d", ErrTaskWrongNumOfArg, len(t.args), ft.NumIn())
}
for i := 0; i < ft.NumIn(); i++ {
funcArgType := ft.In(i)
argType := reflect.TypeOf(t.args[i])
if funcArgType.Kind() != argType.Kind() {
return fmt.Errorf("%w got %s expecting %s", ErrTaskWrongArgType, argType.Name(), funcArgType.Name())
}
}
return nil
}
func (t *Task) updateSchedule() {
t.lastRun = time.Now()
t.nextRun = time.Time{}
if t.tick > 0 {
t.nextRun = t.lastRun.Add(t.tick)
}
}
// Func sets the fuction to execute by the Task
func (t *Task) Func(f interface{}) *Task {
t.fun = f
return t
}
// Args sets the arguments used by the function to execute
func (t *Task) Args(args ...interface{}) *Task {
t.args = args
return t
}
// Schedule schedule a time at which a Task must be ran
func (t *Task) Schedule(next time.Time) *Task {
t.nextRun = next
return t
}
// Tick returns tick value
func (t *Task) Tick() time.Duration {
return t.tick
}
// Ticker sets ticker's duration to run Task at every tick
func (t *Task) Ticker(d time.Duration) *Task {
t.tick = d
if t.nextRun.IsZero() {
t.nextRun = time.Now().Add(d)
}
return t
}
// Async makes the Task asynchronous
func (t *Task) Async() *Task {
t.async = true
return t
}
// IsScheduled returns true if the task is scheduled to run in the future
func (t *Task) IsScheduled() bool {
return t.nextRun.After(time.Now()) || t.ShouldRun()
}
// IsAsync returns true if the task is asynchrone
func (t *Task) IsAsync() bool {
return t.async
}
// IsRunning returns true if the Task is running
func (t *Task) IsRunning() bool {
return t.running
}
// Run runs a Task and returns a error in case the
// function cannot be ran
func (t *Task) Run() (err error) {
t.Lock()
defer t.Unlock()
t.running = true
v := reflect.ValueOf(t.fun)
vargs := make([]reflect.Value, 0, len(t.args))
if err = t.control(); err != nil {
return
}
for _, arg := range t.args {
vargs = append(vargs, reflect.ValueOf(arg))
}
// we schedule next run
t.updateSchedule()
if t.async {
go func() {
defer func() { t.running = false }()
v.Call(vargs)
}()
} else {
defer func() { t.running = false }()
v.Call(vargs)
}
return
}
// ShouldRun returns true if the Task has to run
func (t *Task) ShouldRun() bool {
return !t.nextRun.IsZero() && (t.nextRun.Before(time.Now()) || t.nextRun.Equal(time.Now()))
}