-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathticker.go
68 lines (58 loc) · 978 Bytes
/
ticker.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
package gotk
import (
// "fmt"
"time"
)
type Ticker struct {
status int // 0=init, 1=running, 2=stopped
funcs []func()
duration time.Duration
ch chan struct{}
ticker *time.Ticker
}
func NewTicker(funcs []func(), duration time.Duration) *Ticker {
if len(funcs) <= 0 {
panic("invalid funcs")
}
if duration <= 0 {
panic("invalid duration")
}
return &Ticker{
status: 0,
funcs: funcs,
duration: duration,
ch: make(chan struct{}),
ticker: time.NewTicker(duration),
}
}
func (self *Ticker) Status() int {
return self.status
}
func (self *Ticker) Start() {
self.status = 1
go func() {
ok := true
for {
select {
case <-self.ch:
ok = false
case _, ok = <-self.ticker.C:
}
if !ok {
return
}
for _, fn := range self.funcs {
fn()
}
}
}()
self.status = 1
}
func (self *Ticker) End() {
if self.status != 1 {
return
}
self.ticker.Stop()
self.ch <- struct{}{}
self.status = 2
}