github.com/songzhibin97/gkit@v1.2.13/internal/clock/ticker.go (about)

     1  package clock
     2  
     3  import (
     4  	"sync/atomic"
     5  	"time"
     6  )
     7  
     8  var nowInMs = uint64(0)
     9  
    10  // StartTicker 启动一个后台任务,该任务每毫秒缓存当前时间戳,在高并发情况下可能会提供更好的性能.
    11  func StartTicker() {
    12  	atomic.StoreUint64(&nowInMs, uint64(time.Now().UnixNano())/UnixTimeUnitOffset)
    13  	go func() {
    14  		defer func() {
    15  			if err := recover(); err != nil {
    16  				// no possible
    17  			}
    18  		}()
    19  		for {
    20  			now := uint64(time.Now().UnixNano()) / UnixTimeUnitOffset
    21  			atomic.StoreUint64(&nowInMs, now)
    22  			time.Sleep(time.Millisecond)
    23  		}
    24  	}()
    25  }
    26  
    27  // GetTimestamp 获得当前时间戳,单位是ms
    28  func GetTimestamp() uint64 {
    29  	return atomic.LoadUint64(&nowInMs)
    30  }