forked from koangel/grapeTimer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimerExecute.go
More file actions
275 lines (225 loc) · 5.37 KB
/
Copy pathtimerExecute.go
File metadata and controls
275 lines (225 loc) · 5.37 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/// Author:koangel
/// jackliu100@gmail.com
/// 每个单独的执行模块,结构中越简单越好
package grapeTimer
import (
"encoding/json"
"errors"
"fmt"
"log"
"reflect"
"strconv"
"sync"
"sync/atomic"
"time"
)
const (
// 通过字符串转换下一次的日期
timerDateMode = iota
// 通过转成的Tick日期进行下一次时间计算
timerTickMode
)
type GrapeExecFn interface{}
// 每个执行周期的执行者
// 每个时间执行器
// 可Json化并反Json化
type grapeCallFunc struct {
exeCall GrapeExecFn
args []reflect.Value
status int32
mux sync.Mutex
}
type GrapeTimer struct {
Id int `json:"TimerId"`
NextTime int64 `json:"nextUnix"`
RunMode int `json:"Mode"`
TimeData string `json:"timeData"`
LoopCount int32 `json:"loopCount"` // -1为无限执行
cbFunc *grapeCallFunc
tickSecond int // 临时使用 不可保存
nextVTime time.Time
}
func reflectFunc(fn GrapeExecFn, args ...interface{}) (cb *grapeCallFunc, err error) {
cb = nil
err = nil
t := reflect.TypeOf(fn) // 获得对象类型,从而知道有多少个参数
if t.Kind() != reflect.Func {
err = errors.New("callback must be a function")
return
}
argArr := []interface{}(args) // 先把参数都转成ARRAY
if len(argArr) < t.NumIn() {
err = errors.New("Not enough arguments")
return
}
// 解析全部参数
var in = make([]reflect.Value, t.NumIn()) //MAKE要保存的参数
for i := 0; i < t.NumIn(); i++ {
argType := t.In(i)
if argType != reflect.TypeOf(argArr[i]) {
err = errors.New(fmt.Sprintf("Value not found for type %v", argType))
return
}
in[i] = reflect.ValueOf(argArr[i]) // 参数保存下来
}
cb = &grapeCallFunc{
exeCall: fn,
args: in,
status: 0,
}
return
}
func callFunc(timer *grapeCallFunc) {
// 此处锁一下,防止各种异常
timer.mux.Lock()
defer timer.mux.Unlock()
if timer.status >= 1 && SkipWaitTask {
return
}
// 否则只计数不处理
timer.status++
reflect.ValueOf(timer.exeCall).Call(timer.args) // 正确调用
timer.status--
}
/// 直接创建一个timer 内部函数
func newTimer(Id, Mode, Count int, timeData string, fn GrapeExecFn, args ...interface{}) *GrapeTimer {
cbo, err := reflectFunc(fn, args...)
if err != nil {
fmt.Printf("error:%v", err)
return nil
}
newValue := &GrapeTimer{
Id: Id,
RunMode: Mode,
TimeData: timeData,
LoopCount: int32(Count),
NextTime: 0,
tickSecond: 0,
cbFunc: cbo,
}
newValue.makeNextTime()
return newValue
}
/// 通过Json创建一个Timer 内部函数
func newTimerFromJson(s string, fn GrapeExecFn, args ...interface{}) *GrapeTimer {
cbo, err := reflectFunc(fn, args...)
if err != nil {
fmt.Printf("error:%v", err)
return nil
}
newValue := &GrapeTimer{}
newValue = newValue.ParserJson(s)
if newValue != nil {
newValue.cbFunc = cbo
newValue.makeNextTime()
}
return newValue
}
func (c *GrapeTimer) String() string {
return c.nextVTime.Format(TimeFormat)
}
func (c *GrapeTimer) Format(layout string) string {
return c.nextVTime.Format(layout)
}
/// 执行Timer
func (c *GrapeTimer) Execute() {
if c.IsDestroy() {
return // 销毁中的不可执行
}
if c.IsExpired() {
if CDebugMode {
log.Printf("[grapeTimer] Timer Execute:%v |time:%v| Begin", c.Id, time.Now())
}
// 执行一下
if UseAsyncExec {
go callFunc(c.cbFunc)
} else {
callFunc(c.cbFunc)
}
if CDebugMode {
log.Printf("[grapeTimer] Timer Execute:%v |time:%v| End", c.Id, time.Now())
}
c.nextTime() // 计数
}
}
/// 是否到时间
func (c *GrapeTimer) IsExpired() bool {
if time.Now().Unix() >= c.NextTime {
if CDebugMode {
log.Printf("[grapeTimer] Timer Expired:%v |time:%v|", c.Id, time.Now())
}
return true
}
return false
}
/// 是否可销毁
func (c *GrapeTimer) IsDestroy() bool {
val := atomic.LoadInt32(&c.LoopCount)
if val == -1 {
return false
}
if val == 0 {
return true
}
return false
}
func (c *GrapeTimer) makeNextTime() {
if CDebugMode {
log.Printf("[grapeTimer] Timer Id:%v |time:%v|LoopCount:%v|", c.Id, time.Now(), c.LoopCount)
}
switch c.RunMode {
case timerDateMode:
vtime, err := Parser(c.TimeData)
if err != nil {
atomic.StoreInt32(&c.LoopCount, 0) // 出错销毁
log.Printf("[grapeTimer] Timer Id:%v |time:%v|Error:%v|", c.Id, time.Now(), err)
return
}
c.nextVTime = *vtime
c.NextTime = vtime.Unix() // 生成下一次时间
break
case timerTickMode:
if c.tickSecond == 0 {
c.tickSecond, _ = strconv.Atoi(c.TimeData)
}
vtime := time.Now().Add(time.Duration(c.tickSecond) * time.Millisecond)
c.nextVTime = vtime
c.NextTime = vtime.Unix()
break
}
}
/// 计算下一次时间
func (c *GrapeTimer) nextTime() {
if c.IsDestroy() {
return
}
val := atomic.LoadInt32(&c.LoopCount)
// 先进行计数
if val != -1 {
atomic.AddInt32(&c.LoopCount, -1)
val = atomic.LoadInt32(&c.LoopCount)
if val <= 0 {
val = 0
}
}
c.makeNextTime()
}
func (c *GrapeTimer) Stop() {
atomic.StoreInt32(&c.LoopCount, 0) // 停止这个timer继续执行
}
func (c *GrapeTimer) toJson() string {
bJson, err := json.Marshal(c)
if err != nil {
log.Printf("[grapeTimer] toJson:%v|Error:%v|", c.Id, err)
return ""
}
return string(bJson)
}
func (c *GrapeTimer) ParserJson(s string) *GrapeTimer {
err := json.Unmarshal([]byte(s), c)
if err != nil {
log.Printf("[grapeTimer] ParserJson:%v|Error:%v|", c.Id, err)
return nil
}
return c
}