refactor: move mock time to utils

This commit is contained in:
yusing
2025-04-25 08:21:27 +08:00
parent 5afa93a8f1
commit 59490dcac0
6 changed files with 21 additions and 17 deletions

View File

@@ -0,0 +1,48 @@
package utils
import (
"time"
"github.com/yusing/go-proxy/internal/task"
"go.uber.org/atomic"
)
var (
TimeNow = DefaultTimeNow
shouldCallTimeNow atomic.Bool
timeNowTicker = time.NewTicker(shouldCallTimeNowInterval)
lastTimeNow = time.Now()
)
const shouldCallTimeNowInterval = 100 * time.Millisecond
func MockTimeNow(t time.Time) {
TimeNow = func() time.Time {
return t
}
}
// DefaultTimeNow is a time.Now wrapper that reduces the number of calls to time.Now
// by caching the result and only allow calling time.Now when the ticker fires.
//
// Returned value may have +-100ms error.
func DefaultTimeNow() time.Time {
if shouldCallTimeNow.Load() {
lastTimeNow = time.Now()
shouldCallTimeNow.Store(false)
}
return lastTimeNow
}
func init() {
go func() {
for {
select {
case <-task.RootContext().Done():
return
case <-timeNowTicker.C:
shouldCallTimeNow.Store(true)
}
}
}()
}