github.com/wfusion/gofusion@v1.1.14/common/infra/asynq/pkg/timeutil/timeutil.go (about) 1 // Copyright 2022 Kentaro Hibino. All rights reserved. 2 // Use of this source code is governed by a MIT license 3 // that can be found in the LICENSE file. 4 5 // Package timeutil exports functions and types related to time and date. 6 package timeutil 7 8 import ( 9 "sync" 10 "time" 11 ) 12 13 // A Clock is an object that can tell you the current time. 14 // 15 // This interface allows decoupling code that uses time from the code that creates 16 // a point in time. You can use this to your advantage by injecting Clocks into interfaces 17 // rather than having implementations call time.Now() directly. 18 // 19 // Use RealClock() in production. 20 // Use SimulatedClock() in test. 21 type Clock interface { 22 Now() time.Time 23 } 24 25 func NewRealClock() Clock { return &realTimeClock{} } 26 27 type realTimeClock struct{} 28 29 func (_ *realTimeClock) Now() time.Time { return time.Now() } 30 31 // A SimulatedClock is a concrete Clock implementation that doesn't "tick" on its own. 32 // Time is advanced by explicit call to the AdvanceTime() or SetTime() functions. 33 // This object is concurrency safe. 34 type SimulatedClock struct { 35 mu sync.Mutex 36 t time.Time // guarded by mu 37 } 38 39 func NewSimulatedClock(t time.Time) *SimulatedClock { 40 return &SimulatedClock{t: t} 41 } 42 43 func (c *SimulatedClock) Now() time.Time { 44 c.mu.Lock() 45 defer c.mu.Unlock() 46 return c.t 47 } 48 49 func (c *SimulatedClock) SetTime(t time.Time) { 50 c.mu.Lock() 51 defer c.mu.Unlock() 52 c.t = t 53 } 54 55 func (c *SimulatedClock) AdvanceTime(d time.Duration) { 56 c.mu.Lock() 57 defer c.mu.Unlock() 58 c.t = c.t.Add(d) 59 }