-
Notifications
You must be signed in to change notification settings - Fork 15
/
clockwerk.go
122 lines (102 loc) · 1.95 KB
/
clockwerk.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package clockwerk
import (
"time"
)
// Job is an interface for added jobs.
type Job interface {
Run()
}
// Entry consists of a schedule and the job to execute on that schedule.
type Entry struct {
Period time.Duration
Next time.Time
Prev time.Time
Job Job
}
func newEntry(period time.Duration) *Entry {
return &Entry{
Period: period,
Prev: time.Unix(0, 0),
}
}
// Do adds a Job to the Entry.
func (e *Entry) Do(job Job) {
e.Job = job
}
// Clockwerk keeps track of any number of entries, invoking associated Job's Run
// method as specified by the schedule.
type Clockwerk struct {
entries []*Entry
stop chan struct{}
running bool
}
// New returns a new Clockwerk job runner.
func New() *Clockwerk {
return &Clockwerk{
entries: nil,
stop: make(chan struct{}),
running: false,
}
}
// Every schedules a new Entry and returns it.
func (c *Clockwerk) Every(period time.Duration) *Entry {
entry := newEntry(period)
c.schedule(entry)
if !c.running {
c.entries = append(c.entries, entry)
}
return entry
}
// Start the Clockwerk in its own go-routine, or no-op if already started.
func (c *Clockwerk) Start() {
if c.running {
return
}
c.running = true
go c.run()
}
// Stop the Clockwerk if it is running.
func (c *Clockwerk) Stop() {
if !c.running {
return
}
c.stop <- struct{}{}
c.running = false
}
func (c *Clockwerk) schedule(e *Entry) {
e.Prev = time.Now()
e.Next = e.Prev.Add(e.Period)
}
func (c *Clockwerk) run() {
ticker := time.NewTicker(100 * time.Millisecond)
go func() {
for {
select {
case <-ticker.C:
c.runPending()
continue
case <-c.stop:
ticker.Stop()
return
}
}
}()
}
func (c *Clockwerk) runPending() {
go func() {
for _, entry := range c.entries {
if time.Now().After(entry.Next) {
go c.runJob(entry)
}
}
}()
}
func (c *Clockwerk) runJob(e *Entry) {
defer func() {
if r := recover(); r != nil {
c.schedule(e)
}
}()
c.schedule(e)
e.Job.Run()
}