-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
group.go
68 lines (56 loc) · 1.15 KB
/
group.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
package background
import "sync"
func NewGroup() *Group {
return &Group{
m: map[string]*Background{},
}
}
// Group 执行信息
type Group struct {
m map[string]*Background
mu sync.RWMutex
}
// Cancel 取消某个任务
func (e *Group) Cancel(cacheKeys ...string) {
if len(cacheKeys) == 0 {
return
}
e.mu.Lock()
e.cancel(cacheKeys...)
e.mu.Unlock()
}
func (e *Group) cancel(cacheKeys ...string) {
for _, cacheKey := range cacheKeys {
if bgExec, ok := (*e).m[cacheKey]; ok {
bgExec.cancel()
delete((*e).m, cacheKey)
}
}
}
// Exists 任务是否存在
func (e *Group) Exists(cacheKey string) bool {
e.mu.RLock()
_, ok := (*e).m[cacheKey]
e.mu.RUnlock()
return ok
}
// Map 任务列表
func (e *Group) Map() map[string]Background {
r := map[string]Background{}
e.mu.RLock()
for k, v := range (*e).m {
if v != nil {
r[k] = *v
}
}
e.mu.RUnlock()
return r
}
// Add 新增任务
func (e *Group) Add(op string, cacheKey string, bgExec *Background) {
e.mu.Lock()
e.cancel(cacheKey) // 避免被覆盖后旧任务失去控制,先取消已存在的任务
(*e).m[cacheKey] = bgExec
e.mu.Unlock()
Backgrounds.Store(op, e)
}