From ed3b06f3bfd0788517bd84d0f72f236055e0c6b3 Mon Sep 17 00:00:00 2001 From: Siyuan Miao Date: Sat, 15 Feb 2025 19:27:24 +0100 Subject: [PATCH] feat(ntp): add delay between time sync attempts --- ntp.go | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/ntp.go b/ntp.go index 4150d96..91f7b90 100644 --- a/ntp.go +++ b/ntp.go @@ -11,11 +11,19 @@ import ( "github.com/beevik/ntp" ) -var timeSynced = false -var defaultNTPServers = []string{ - "time.cloudflare.com", - "time.apple.com", -} +const ( + timeSyncRetryStep = 5 * time.Second + timeSyncRetryMaxInt = 1 * time.Minute +) + +var ( + timeSynced = false + timeSyncRetryInterval = 0 * time.Second + defaultNTPServers = []string{ + "time.cloudflare.com", + "time.apple.com", + } +) func TimeSyncLoop() { for { @@ -30,6 +38,15 @@ func TimeSyncLoop() { err := SyncSystemTime() if err != nil { 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 } log.Printf("Time sync successful, now is: %v, time taken: %v", time.Now(), time.Since(start))