github.com/zerjioang/time32@v0.0.0-20211102104504-b756043b9843/ticker.go (about) 1 // 2 // Created by zerjioang 3 // https://github/zerjioang 4 // Copyright (c) 2020. All rights reserved. 5 // 6 // SPDX-License-Identifier: GPL-3.0 7 // 8 9 package time32 10 11 import ( 12 "sync/atomic" 13 "time" 14 ) 15 16 // lastTime stores the epoch value of last time reading 17 var lastTime atomic.Value 18 var lastUnix atomic.Value 19 var lastUnixNano atomic.Value 20 21 func init() { 22 // store initial value 23 tt := time.Now() 24 lastTime.Store(tt) 25 lastUnix.Store(tt.Unix()) 26 lastUnixNano.Store(tt.UnixNano()) 27 28 // run each 0.1 seconds (aka precision) 29 ticker := time.NewTicker(100 * time.Millisecond) 30 go func() { 31 for { 32 select { 33 case t := <-ticker.C: 34 lastTime.Store(t) 35 lastUnix.Store(t.Unix()) 36 lastUnixNano.Store(t.UnixNano()) 37 } 38 } 39 }() 40 } 41 42 // ReuseTime is a function that reuses last readed epoch value 43 // this function is meant to be used on high demanding applications that require 44 // time value readings with high frequency. Instead of making a syscall on every request, 45 // last time value is cached. Cache duration has a window of 0.1s so all calls requested during 46 // that period will reuse the same epoch time value 47 func ReuseTime() time.Time { 48 return lastTime.Load().(time.Time) 49 } 50 51 func ReuseUnix() int64 { 52 return lastUnix.Load().(int64) 53 } 54 55 func ReuseUnixNano() int64 { 56 return lastUnixNano.Load().(int64) 57 }