新增时间偏移

This commit is contained in:
boyce
2025-10-09 17:22:09 +08:00
parent 419e7ee0c4
commit f22ee230e4

View File

@@ -6,21 +6,21 @@ import (
"time" "time"
) )
func SetupTimer(timer ITimer) ITimer{ func SetupTimer(timer ITimer) ITimer {
if timer.IsOpen() == true { if timer.IsOpen() == true {
return nil return nil
} }
timer.Open(true) timer.Open(true)
timerHeapLock.Lock() // 使用锁规避竞争条件 timerHeapLock.Lock() // 使用锁规避竞争条件
heap.Push(&timerHeap,timer) heap.Push(&timerHeap, timer)
timerHeapLock.Unlock() timerHeapLock.Unlock()
return timer return timer
} }
func NewTimer(d time.Duration) *Timer{ func NewTimer(d time.Duration) *Timer {
c := make(chan ITimer,1) c := make(chan ITimer, 1)
timer := newTimer(d,c,nil,"") timer := newTimer(d, c, nil, "")
SetupTimer(timer) SetupTimer(timer)
return timer return timer
@@ -43,7 +43,7 @@ func (h *_TimerHeap) Less(i, j int) bool {
} }
func (h *_TimerHeap) Swap(i, j int) { func (h *_TimerHeap) Swap(i, j int) {
h.timers[i],h.timers[j] = h.timers[j],h.timers[i] h.timers[i], h.timers[j] = h.timers[j], h.timers[i]
} }
func (h *_TimerHeap) Push(x interface{}) { func (h *_TimerHeap) Push(x interface{}) {
@@ -62,16 +62,16 @@ var (
timeOffset time.Duration timeOffset time.Duration
) )
func StartTimer(minTimerInterval time.Duration,maxTimerNum int){ func StartTimer(minTimerInterval time.Duration, maxTimerNum int) {
timerHeap.timers = make([]ITimer,0,maxTimerNum) timerHeap.timers = make([]ITimer, 0, maxTimerNum)
heap.Init(&timerHeap) // 初始化定时器heap heap.Init(&timerHeap) // 初始化定时器heap
go tickRoutine(minTimerInterval) go tickRoutine(minTimerInterval)
} }
func tickRoutine(minTimerInterval time.Duration){ func tickRoutine(minTimerInterval time.Duration) {
var bContinue bool var bContinue bool
for{ for {
bContinue = tick() bContinue = tick()
if bContinue == false { if bContinue == false {
time.Sleep(minTimerInterval) time.Sleep(minTimerInterval)
@@ -79,7 +79,7 @@ func tickRoutine(minTimerInterval time.Duration){
} }
} }
func tick() bool{ func tick() bool {
now := Now() now := Now()
timerHeapLock.Lock() timerHeapLock.Lock()
if timerHeap.Len() <= 0 { // 没有任何定时器,立刻返回 if timerHeap.Len() <= 0 { // 没有任何定时器,立刻返回
@@ -100,7 +100,7 @@ func tick() bool{
return true return true
} }
func Now() time.Time{ func Now() time.Time {
if timeOffset == 0 { if timeOffset == 0 {
return time.Now() return time.Now()
} }
@@ -108,4 +108,7 @@ func Now() time.Time{
return time.Now().Add(timeOffset) return time.Now().Add(timeOffset)
} }
// SetTimeOffset 设置时间偏移量
func SetTimeOffset(offset time.Duration) {
timeOffset = offset
}