-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
158 lines (134 loc) · 2.91 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
package task
import (
"context"
"errors"
"fmt"
"runtime/debug"
"time"
"go.uber.org/atomic"
)
var (
TaskDefaultExecuteTimeout = time.Second * 5 // execute timeout
TaskDefaultTimeout = time.Hour * 24 * 30 * 12 // default timeout
TaskDefaultSleep = time.Millisecond * 500 // sleep time 500ms
ErrTimeout = errors.New("time out")
)
type TaskHandler func(context.Context, ...interface{}) error
type Task struct {
c context.Context // control run timeout
f TaskHandler // handle function
e chan<- error // error returned
p []interface{} // params in order
}
type Tasker struct {
opts *TaskerOptions
tasks chan *Task
running atomic.Bool
}
func NewTasker(max int32) *Tasker {
return &Tasker{
opts: &TaskerOptions{},
tasks: make(chan *Task, max),
}
}
func (t *Tasker) Init(opts ...TaskerOption) {
t.opts = defaultTaskerOptions()
for _, o := range opts {
o(t.opts)
}
}
func (t *Tasker) ResetTimer() {
tm := t.opts.timer
if tm != nil && !tm.Stop() {
<-tm.C
}
tm.Reset(t.opts.d)
}
func (t *Tasker) IsRunning() bool {
return t.running.Load()
}
func (t *Tasker) AddWait(ctx context.Context, f TaskHandler, p ...interface{}) error {
subCtx, cancel := context.WithTimeout(ctx, TaskDefaultExecuteTimeout)
defer cancel()
e := make(chan error, 1)
tk := &Task{
c: subCtx,
f: f,
e: e,
p: make([]interface{}, 0, len(p)),
}
tk.p = append(tk.p, p...)
t.tasks <- tk
select {
case err := <-e:
if err == nil {
return nil
}
return fmt.Errorf("task add with error:%w, chan buff size:%d", err, len(t.tasks))
case <-subCtx.Done():
if subCtx.Err() == nil {
return nil
}
return fmt.Errorf("task add with timeout:%w, chan buff size:%d", subCtx.Err(), len(t.tasks))
}
}
func (t *Tasker) Add(ctx context.Context, f TaskHandler, p ...interface{}) {
tk := &Task{
c: ctx,
f: f,
e: nil,
p: make([]interface{}, 0, len(p)),
}
tk.p = append(tk.p, p...)
t.tasks <- tk
}
func (t *Tasker) Run(ctx context.Context) error {
t.running.Store(true)
defer func() {
if err := recover(); err != nil {
stack := string(debug.Stack())
fmt.Printf("catch exception:%v, panic recovered with stack:%s", err, stack)
}
t.running.Store(false)
}()
if len(t.opts.startFns) > 0 {
for _, fn := range t.opts.startFns {
fn()
}
}
for {
select {
case <-ctx.Done():
if t.opts.ctxFn != nil {
t.opts.ctxFn() // context done callback
}
return nil
case h, ok := <-t.tasks:
if !ok {
return nil
} else {
err := h.f(h.c, h.p...)
if h.e != nil {
h.e <- err // handle result
}
if err == nil {
continue
}
}
case <-t.opts.timer.C:
return ErrTimeout
default:
now := time.Now()
if t.opts.updateFn != nil {
t.opts.updateFn() // update callback
}
d := time.Since(now)
time.Sleep(t.opts.sleep - d)
}
}
}
func (t *Tasker) Stop() {
t.running.Store(false)
close(t.tasks)
t.opts.timer.Stop()
}