time.go 836 B

1234567891011121314151617181920212223242526272829303132
  1. package utils
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "time"
  6. )
  7. var (
  8. timestampTimer sync.Once
  9. // Timestamp please start the timer function before you use this value
  10. // please load the value with atomic `atomic.LoadUint32(&utils.Timestamp)`
  11. Timestamp uint32
  12. )
  13. // StartTimeStampUpdater starts a concurrent function which stores the timestamp to an atomic value per second,
  14. // which is much better for performance than determining it at runtime each time
  15. func StartTimeStampUpdater() {
  16. timestampTimer.Do(func() {
  17. // set initial value
  18. atomic.StoreUint32(&Timestamp, uint32(time.Now().Unix()))
  19. go func(sleep time.Duration) {
  20. ticker := time.NewTicker(sleep)
  21. defer ticker.Stop()
  22. for t := range ticker.C {
  23. // update timestamp
  24. atomic.StoreUint32(&Timestamp, uint32(t.Unix()))
  25. }
  26. }(1 * time.Second) // duration
  27. })
  28. }