-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtimertask.go
77 lines (67 loc) · 1.39 KB
/
timertask.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
package gotimertask
import "time"
type TimerTask struct {
task *Task
duration time.Duration
ticker *time.Ticker
exit chan bool
stopped bool
}
type Task struct {
run func(interface{})
data interface{}
}
// Creates a new Task with argument which needs to be passed to a function to be scheduled
func NewTaskWithArgument(f func(interface{}), arg interface{}) *Task {
return &Task{
run: f,
data: arg,
}
}
// Creates a new Task without argument which needs to be passed to a function to be scheduled
func NewTask(f func()) *Task {
run := func(interface{}) {
f()
}
return &Task{
run: run,
}
}
// Stops the given timer task from further execution
// Once stopped it won't run again
// and again invoking Stop() doesn't do anything
func (t *TimerTask) Stop() {
if !t.stopped {
t.exit <- true
t.stopped = true
close(t.exit)
}
}
func newTimerTask(t *Task, d time.Duration) *TimerTask {
return &TimerTask{
task: t,
duration: d,
ticker: time.NewTicker(d),
exit: make(chan bool),
stopped: false,
}
}
// Schedules a function `f` to run at a `d` Duration
func Schedule(t *Task, d time.Duration) *TimerTask {
timerTask := newTimerTask(t, d)
taskInvoker(timerTask)
return timerTask
}
func taskInvoker(t *TimerTask) {
go func() {
for {
select {
case <-t.ticker.C:
t.task.run(t.task.data)
case <-t.exit:
t.ticker.Stop()
return
}
}
}()
}