-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
beatschedule.go
58 lines (49 loc) · 1.08 KB
/
beatschedule.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
package core
import (
"sync"
"time"
)
// BeatSchedule holds mapping between beat counts and an action (function).
type BeatSchedule struct {
mutex *sync.RWMutex
entries map[int64][]BeatAction
}
type BeatAction func(when time.Time)
func NewBeatSchedule() *BeatSchedule {
return &BeatSchedule{
mutex: new(sync.RWMutex),
entries: map[int64][]BeatAction{},
}
}
func (s *BeatSchedule) IsEmpty() bool {
s.mutex.RLock()
defer s.mutex.RUnlock()
return len(s.entries) == 0
}
func (s *BeatSchedule) Reset() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.entries = map[int64][]BeatAction{}
}
func (s *BeatSchedule) Schedule(beat int64, action BeatAction) {
s.mutex.Lock()
defer s.mutex.Unlock()
actions, ok := s.entries[beat]
if ok {
actions = append(actions, action)
} else {
actions = []BeatAction{action}
}
s.entries[beat] = actions
}
var noActions = []BeatAction{}
func (s *BeatSchedule) Unschedule(beat int64) []BeatAction {
s.mutex.Lock()
defer s.mutex.Unlock()
actions, ok := s.entries[beat]
if !ok {
return noActions
}
delete(s.entries, beat)
return actions
}