-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmanager.go
97 lines (85 loc) · 1.67 KB
/
manager.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
package go_task
import (
"container/list"
"fmt"
"sync"
"time"
)
type queue struct {
list.List
}
// Add 按照执行顺序添加
func (q *queue) Add(task *Task) *list.Element {
next := task.NextTick()
for item := q.Back(); item != nil; item = item.Prev() {
t := item.Value.(*Task)
if next >= t.NextTick() {
return q.InsertAfter(task, item)
}
}
return q.PushFront(task)
}
type Manager struct {
items map[string]*Task
readyQueue queue // 准备队列
lock sync.RWMutex
}
func (m *Manager) runTask(task *Task) {
task.Run()
m.lock.Lock()
if !task.ctx.IsCanceled() {
task.e = m.readyQueue.Add(task)
}
m.lock.Unlock()
}
func (m *Manager) scheduleOnce() {
for m.readyQueue.Len() > 0 {
item := m.readyQueue.Front()
task := item.Value.(*Task)
if !task.Can() {
break
}
task.e = nil
m.readyQueue.Remove(item)
go m.runTask(task)
}
}
func (m *Manager) schedule() {
for {
time.Sleep(time.Second) // 每秒执行一次
m.lock.Lock()
m.scheduleOnce()
m.lock.Unlock()
}
}
func (m *Manager) Add(task *Task) error {
m.lock.Lock()
defer m.lock.Unlock()
if _, ok := m.items[task.key]; ok {
return fmt.Errorf("already existed: %v", task.key)
}
m.items[task.key] = task
go m.runTask(task)
return nil
}
func (m *Manager) Delete(key string) error {
m.lock.Lock()
defer m.lock.Unlock()
if task, ok := m.items[key]; !ok {
return fmt.Errorf("not existed key: %v", key)
} else {
task.ctx.setCanceled()
if task.e != nil { // not running state
m.readyQueue.Remove(task.e)
}
delete(m.items, key)
}
return nil
}
func NewManager() *Manager {
mgr := &Manager{
items: make(map[string]*Task, 0),
}
go mgr.schedule()
return mgr
}