-
Notifications
You must be signed in to change notification settings - Fork 882
/
loop.go
105 lines (75 loc) · 1.66 KB
/
loop.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
package timer
import (
"github.com/davyxu/cellnet"
"sync/atomic"
"time"
)
// 轻量级的持续Tick循环
type Loop struct {
Context interface{}
Duration time.Duration
userCallback func(*Loop)
running int64
Queue cellnet.EventQueue
}
func (self *Loop) Running() bool {
return atomic.LoadInt64(&self.running) != 0
}
func (self *Loop) setRunning(v bool) {
if v {
atomic.StoreInt64(&self.running, 1)
} else {
atomic.StoreInt64(&self.running, 0)
}
}
// 开始Tick
func (self *Loop) Start() bool {
if self.Running() {
return false
}
atomic.StoreInt64(&self.running, 1)
self.rawPost()
return true
}
func (self *Loop) rawPost() {
if self.Duration == 0 {
panic("seconds can be zero in loop")
}
if self.Running() {
After(self.Queue, self.Duration, func() {
tick(self, false)
}, nil)
}
}
func (self *Loop) NextLoop() {
self.Queue.Post(func() {
tick(self, true)
})
}
func (self *Loop) Stop() {
self.setRunning(false)
}
// 马上调用一次用户回调
func (self *Loop) Notify() *Loop {
self.userCallback(self)
return self
}
func tick(ctx interface{}, nextLoop bool) {
loop := ctx.(*Loop)
if !nextLoop && loop.Running() {
// 即便在Notify中发生了崩溃,也会使用defer再次继续循环
defer loop.rawPost()
}
loop.Notify()
}
// 执行一个循环, 持续调用callback, 周期是duration
// context: 将context上下文传递到带有context指针的函数回调中
func NewLoop(q cellnet.EventQueue, duration time.Duration, callback func(*Loop), context interface{}) *Loop {
self := &Loop{
Context: context,
Duration: duration,
userCallback: callback,
Queue: q,
}
return self
}