/
task.go
83 lines (73 loc) · 1.1 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
package task
import (
"context"
"go.uber.org/atomic"
"sync"
"time"
)
type task struct {
MaxLimit int64
stop *atomic.Bool
sync.Pool
Err error
}
// Run ...
func (t *task) Run() {
runs := atomic.NewInt64(0)
ctx, cancel := context.WithCancel(context.TODO())
for {
if t.stop.Load() {
cancel()
break
}
if runs.Load() <= t.MaxLimit {
runs.Add(1)
go func() {
defer runs.Add(-1)
for v := t.Get(); v != nil; {
if fn, b := v.(CallFunc); b {
fn(ctx)
}
}
}()
}
}
for {
if runs.Load() == 0 {
return
}
//only wait 3 sec
time.Sleep(3 * time.Second)
return
}
}
// AddCall ...
func (t *task) AddCall(callFunc CallFunc) {
t.Put(callFunc)
}
// Waiting ...
func (t *task) Waiting() {
for {
if t.stop.Load() {
return
}
//every 5 sec check once
time.Sleep(5 * time.Second)
}
}
// CallFunc ...
type CallFunc func(ctx context.Context)
// Task ...
type Task interface {
Run()
AddCall(callFunc CallFunc)
Waiting()
}
// New ...
func New() Task {
return &task{
stop: atomic.NewBool(false),
MaxLimit: 0,
Pool: sync.Pool{},
}
}