github.com/gofiber/fiber/v2@v2.47.0/utils/time.go (about)

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