-
Notifications
You must be signed in to change notification settings - Fork 0
/
x_sched.go
75 lines (66 loc) · 1.33 KB
/
x_sched.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 timer
import (
"time"
"github.com/benz9527/xboot/lib/hrtime"
)
type xScheduler struct {
intervals []time.Duration
currentIndex int
isFinite bool
}
var (
_ Scheduler = (*xScheduler)(nil)
)
func NewFiniteScheduler(intervals ...time.Duration) Scheduler {
if len(intervals) == 0 {
return nil
}
for _, interval := range intervals {
if interval.Milliseconds() <= 0 {
return nil
}
}
return &xScheduler{
isFinite: true,
intervals: intervals,
currentIndex: 0,
}
}
func NewInfiniteScheduler(intervals ...time.Duration) Scheduler {
if len(intervals) == 0 {
return nil
}
for _, interval := range intervals {
if interval.Milliseconds() <= 0 {
return nil
}
}
return &xScheduler{
intervals: intervals,
currentIndex: 0,
}
}
func (x *xScheduler) next(beginMs int64) (nextExpiredMs int64) {
beginTime := hrtime.MillisToDefaultTzTime(beginMs)
if beginTime.IsZero() || len(x.intervals) == 0 {
return -1
}
if x.currentIndex >= len(x.intervals) {
if x.isFinite {
return -1
}
x.currentIndex = 0
}
if x.intervals[x.currentIndex].Milliseconds() <= 0 {
return -1
}
next := beginTime.Add(x.intervals[x.currentIndex])
x.currentIndex++
return next.UnixMilli()
}
func (x *xScheduler) GetRestLoopCount() int64 {
if x.isFinite {
return int64(len(x.intervals) - x.currentIndex)
}
return -1
}