-
Notifications
You must be signed in to change notification settings - Fork 0
/
chronos.go
49 lines (43 loc) · 1.12 KB
/
chronos.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
package chronos
// creates a new task which executes under the given schedule
func NewScheduledTask(action func(), schedule TaskSchedule) ScheduledTask {
task := ScheduledTask{}
task.action = action
task.schedule = schedule
task.executeSignal = make(chan struct{})
task.abortSignal = make(chan struct{})
return task
}
// a task which's action executes by the given schedule.
type ScheduledTask struct {
action func()
schedule TaskSchedule
executeSignal chan struct{}
abortSignal chan struct{}
}
func (st *ScheduledTask) Stop() {
st.abortSignal <- struct{}{}
}
// starts the scheduling (non-blocking)
func (st *ScheduledTask) Start() {
// should use the New... functions to create a schedule
if st.schedule.Plan == 0 {
panic("schedule has no plan defined")
}
// initialize plan
scheduleAbortSignal := make(chan struct{}, 1)
go st.schedule.Init(st.executeSignal, scheduleAbortSignal)
// listen for signals to process the task
go func() {
exit:
for {
select {
case <-st.executeSignal:
go st.action()
case <-st.abortSignal:
scheduleAbortSignal <- struct{}{}
break exit
}
}
}()
}