| 1 | package utils |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | "sync/atomic" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | var ( |
| 10 | timestamp atomic.Uint32 |
| 11 | updaterMu sync.Mutex |
| 12 | stopUpdater chan struct{} |
| 13 | updaterDone chan struct{} |
| 14 | ) |
| 15 | |
| 16 | // Timestamp returns the current cached Unix timestamp (seconds). |
| 17 | // Call StartTimeStampUpdater() once at app startup for best performance. |
| 18 | func Timestamp() uint32 { |
| 19 | return timestamp.Load() |
| 20 | } |
| 21 | |
| 22 | // StartTimeStampUpdater launches a background goroutine that updates the cached timestamp every second. |
| 23 | // It is safe to call multiple times and from multiple goroutines; only one updater runs at a time. |
| 24 | func StartTimeStampUpdater() { |
| 25 | updaterMu.Lock() |
| 26 | defer updaterMu.Unlock() |
| 27 | if stopUpdater != nil { |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | timestamp.Store(uint32(time.Now().Unix())) |
| 32 | stopUpdater = make(chan struct{}) |
| 33 | updaterDone = make(chan struct{}) |
| 34 | |
| 35 | go func(stop, done chan struct{}) { |
| 36 | ticker := time.NewTicker(time.Second) |
| 37 | defer ticker.Stop() |
| 38 | defer close(done) |
| 39 | |
| 40 | for { |
| 41 | select { |
| 42 | case <-ticker.C: |
| 43 | timestamp.Store(uint32(time.Now().Unix())) |
| 44 | case <-stop: |
| 45 | return |
| 46 | } |
| 47 | } |
| 48 | }(stopUpdater, updaterDone) |
| 49 | } |
| 50 | |
| 51 | // StopTimeStampUpdater stops the background updater goroutine. |
| 52 | // Call this on app shutdown to avoid leaking goroutines. |
| 53 | // It is safe to call multiple times and from multiple goroutines. |
| 54 | func StopTimeStampUpdater() { |
| 55 | updaterMu.Lock() |
| 56 | defer updaterMu.Unlock() |
| 57 | if stopUpdater == nil { |
| 58 | return |
| 59 | } |
| 60 | |
| 61 | close(stopUpdater) |
| 62 | <-updaterDone |
| 63 | stopUpdater = nil |
| 64 | updaterDone = nil |
| 65 | } |