-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
EmitQueue.go
92 lines (79 loc) · 1.53 KB
/
EmitQueue.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
package utils
import (
"github.com/Logiase/MiraiGo-Template/utils"
"github.com/Sora233/DDBOT/concern"
pq "github.com/jupp0r/go-priority-queue"
"sync"
"time"
)
var logger = utils.GetModuleLogger("utils")
type EmitE struct {
Id interface{}
Type concern.Type
}
func NewEmitE(id interface{}, t concern.Type) *EmitE {
return &EmitE{
Id: id,
Type: t,
}
}
type EmitQueue struct {
*sync.Cond
TimeInterval time.Duration
pq pq.PriorityQueue
emitChan chan<- *EmitE
waitTimer *time.Timer
}
func (q *EmitQueue) Add(e *EmitE, t time.Time) {
q.L.Lock()
defer q.L.Unlock()
q.pq.Insert(e, float64(t.Unix()))
if q.pq.Len() == 1 {
q.Signal()
}
}
func (q *EmitQueue) core() {
for {
q.L.Lock()
for q.pq.Len() == 0 {
q.Wait()
}
q.L.Unlock()
<-q.waitTimer.C
q.L.Lock()
e, err := q.pq.Pop()
if err != nil {
logger.Errorf("pop from pq failed %v", err)
q.L.Unlock()
} else {
if ee, ok := e.(*EmitE); ok {
select {
case q.emitChan <- ee:
default:
q.L.Unlock()
q.emitChan <- ee
q.L.Lock()
}
} else {
logger.Errorf("can not cast type %T", ee)
}
q.pq.Insert(e, float64(time.Now().Unix()))
q.L.Unlock()
}
q.waitTimer.Reset(q.TimeInterval)
}
}
func (q *EmitQueue) Stop() {
// TODO
}
func NewEmitQueue(c chan<- *EmitE, interval time.Duration) *EmitQueue {
q := &EmitQueue{
pq: pq.New(),
Cond: sync.NewCond(new(sync.Mutex)),
emitChan: c,
waitTimer: time.NewTimer(interval),
TimeInterval: interval,
}
go q.core()
return q
}