/
gtimer_timer_loop.go
67 lines (61 loc) · 1.74 KB
/
gtimer_timer_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
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gtimer
import "time"
// loop starts the ticker using a standalone goroutine.
func (t *Timer) loop() {
go func() {
var (
currentTimerTicks int64
timerIntervalTicker = time.NewTicker(t.options.Interval)
)
defer timerIntervalTicker.Stop()
for {
select {
case <-timerIntervalTicker.C:
// Check the timer status.
switch t.status.Val() {
case StatusRunning:
// Timer proceeding.
if currentTimerTicks = t.ticks.Add(1); currentTimerTicks >= t.queue.NextPriority() {
t.proceed(currentTimerTicks)
}
case StatusStopped:
// Do nothing.
case StatusClosed:
// Timer exits.
return
}
}
}
}()
}
// proceed function proceeds the timer job checking and running logic.
func (t *Timer) proceed(currentTimerTicks int64) {
var (
value interface{}
)
for {
value = t.queue.Pop()
if value == nil {
break
}
entry := value.(*Entry)
// It checks if it meets the ticks' requirement.
if jobNextTicks := entry.nextTicks.Val(); currentTimerTicks < jobNextTicks {
// It pushes the job back if current ticks does not meet its running ticks requirement.
t.queue.Push(entry, entry.nextTicks.Val())
break
}
// It checks the job running requirements and then does asynchronous running.
entry.doCheckAndRunByTicks(currentTimerTicks)
// Status check: push back or ignore it.
if entry.Status() != StatusClosed {
// It pushes the job back to queue for next running.
t.queue.Push(entry, entry.nextTicks.Val())
}
}
}