-
Notifications
You must be signed in to change notification settings - Fork 280
/
scheduler.go
85 lines (72 loc) · 1.72 KB
/
scheduler.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
// Package scheduler contains a priority queue based on time.
package scheduler
import (
"strings"
"time"
"github.com/google/btree"
)
var maxTime = time.Unix(1<<63-62135596801, 999999999)
type itemByKey struct {
time time.Time
key string
}
func (i itemByKey) Less(than btree.Item) bool {
return strings.Compare(i.key, than.(itemByKey).key) < 0
}
type itemByTime struct {
time time.Time
key string
}
func (i itemByTime) Less(than btree.Item) bool {
xTime, yTime := i.time, than.(itemByTime).time
switch {
case xTime.Before(yTime):
return true
case yTime.Before(xTime):
return false
}
return itemByKey(i).Less(itemByKey(than.(itemByTime)))
}
// A Scheduler implements a priority queue based on time. The scheduler is not thread-safe for multiple writers.
type Scheduler struct {
byTime *btree.BTree
byKey *btree.BTree
}
// New creates a new Scheduler.
func New() *Scheduler {
return &Scheduler{
byTime: btree.New(8),
byKey: btree.New(8),
}
}
// Add adds an item to the scheduler.
func (s *Scheduler) Add(due time.Time, key string) {
i := s.byKey.Get(itemByKey{key: key})
if i != nil {
s.byTime.Delete(itemByTime(i.(itemByKey)))
}
s.byKey.ReplaceOrInsert(itemByKey{
time: due,
key: key,
})
s.byTime.ReplaceOrInsert(itemByTime{
time: due,
key: key,
})
}
// Remove removes an item from the scheduler and de-schedules it.
func (s *Scheduler) Remove(key string) {
i := s.byKey.Get(itemByKey{key: key})
if i != nil {
s.byKey.Delete(i)
s.byTime.Delete(itemByTime(i.(itemByKey)))
}
}
// Next retrieves the next time an item is due.
func (s *Scheduler) Next() (time.Time, string) {
if s.byTime.Len() == 0 {
return maxTime, ""
}
item := s.byTime.Min().(itemByTime)
return item.time, item.key
}