feat(ntp): add delay between time sync attempts

This commit is contained in:
Siyuan Miao 2025-02-15 19:27:24 +01:00
parent d77d6e941d
commit ed3b06f3bf
1 changed files with 22 additions and 5 deletions

23
ntp.go
View File

@ -11,11 +11,19 @@ import (
"github.com/beevik/ntp" "github.com/beevik/ntp"
) )
var timeSynced = false const (
var defaultNTPServers = []string{ timeSyncRetryStep = 5 * time.Second
timeSyncRetryMaxInt = 1 * time.Minute
)
var (
timeSynced = false
timeSyncRetryInterval = 0 * time.Second
defaultNTPServers = []string{
"time.cloudflare.com", "time.cloudflare.com",
"time.apple.com", "time.apple.com",
} }
)
func TimeSyncLoop() { func TimeSyncLoop() {
for { for {
@ -30,6 +38,15 @@ func TimeSyncLoop() {
err := SyncSystemTime() err := SyncSystemTime()
if err != nil { if err != nil {
log.Printf("Failed to sync system time: %v", err) log.Printf("Failed to sync system time: %v", err)
// retry after a delay
timeSyncRetryInterval += timeSyncRetryStep
time.Sleep(timeSyncRetryInterval)
// reset the retry interval if it exceeds the max interval
if timeSyncRetryInterval > timeSyncRetryMaxInt {
timeSyncRetryInterval = 0
}
continue continue
} }
log.Printf("Time sync successful, now is: %v, time taken: %v", time.Now(), time.Since(start)) log.Printf("Time sync successful, now is: %v, time taken: %v", time.Now(), time.Since(start))