-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
75 lines (64 loc) · 1.33 KB
/
timer.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
package goutils
import (
"time"
)
// go lib timer struct, use NewTimer to create.
// handler will execute after 1 second in example below
//
// func handler(p interface{}) {
// i := p.(int)
// fmt.Println(i)
// }
//
// timer := golib.NewTimer(1 * time.Second, handler, 10)
type Timer struct {
timer *time.Timer
quit chan bool
handler func(d interface{})
data interface{}
}
func (timer *Timer) startTimer(d time.Duration) {
timer.timer = time.NewTimer(d)
go func() {
select {
case <-timer.timer.C:
if timer.handler != nil {
timer.handler(timer.data)
}
case <-timer.quit:
return
}
}()
}
// NewTimer creates a new Timer,
// that will call function f with paras p after duration d
func NewTimer(d time.Duration, f func(interface{}), p interface{}) *Timer {
timer := &Timer{
quit: make(chan bool),
handler: f,
data: p,
}
timer.startTimer(d)
return timer
}
// Stop prevents the Timer From firing
func (t *Timer) Stop() {
if t.timer == nil {
return
}
if t.timer.Stop() {
// timer had been active
t.quit <- true
}
}
// Reset changes the timer to expire after duration d,
// if timer had expired or been stoped, it will restart timer again
func (t *Timer) Reset(d time.Duration) {
if t.timer == nil {
return
}
if !t.timer.Reset(d) {
// timer had expired or been stopped
t.startTimer(d)
}
}