-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.go
More file actions
56 lines (48 loc) · 1.05 KB
/
queue.go
File metadata and controls
56 lines (48 loc) · 1.05 KB
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
package dqueue
import (
"time"
)
type queue struct {
nextOn time.Time
tasks []*Task
}
// Len is used for implementing sort.Interface.
func (dq *queue) Len() int {
return len(dq.tasks)
}
// Less is used for implementing sort.Interface.
func (dq *queue) Less(i, j int) bool {
return dq.tasks[i].ExecuteAt.Before(dq.tasks[j].ExecuteAt)
}
// Swap is used for implementing sort.Interface.
func (dq *queue) Swap(i, j int) {
dq.tasks[i], dq.tasks[j] = dq.tasks[j], dq.tasks[i]
}
// Push is used for implementing heap.Interface.
func (dq *queue) Push(x any) {
item, ok := x.(*Task)
if !ok {
return
}
if item.ExecuteAt.Before(time.Now()) {
return
}
if item.ExecuteAt.Before(dq.nextOn) {
dq.nextOn = item.ExecuteAt
}
dq.tasks = append(dq.tasks, item)
}
// Pop is used for implementing heap.Interface.
func (dq *queue) Pop() any {
old := dq.tasks
n := len(old)
item := old[n-1]
old[n-1] = nil
dq.tasks = old[0 : n-1]
dq.nextOn = item.ExecuteAt
return item
}
func (dq *queue) prune() {
dq.nextOn = time.Now().Add(maxNextInterval)
dq.tasks = nil
}