jonboulle/clockwork — v0.5.0 snapshot¶
Pinned: v0.5.0 Source: tagged source
Interface¶
type Clock interface {
After(d time.Duration) <-chan time.Time
Sleep(d time.Duration)
Now() time.Time
Since(t time.Time) time.Duration
Until(t time.Time) time.Duration
NewTicker(d time.Duration) Ticker
NewTimer(d time.Duration) Timer
AfterFunc(d time.Duration, f func()) Timer
}
Real clock¶
Fake clock (tests)¶
fc := clockwork.NewFakeClock() // starts at current system time
fc := clockwork.NewFakeClockAt(t) // deterministic start time
now := fc.Now()
fc.Advance(5 * time.Minute) // advance time
if err := fc.BlockUntilContext(ctx, 1); err != nil {
return fmt.Errorf("wait for clock consumer: %w", err)
}
Usage pattern¶
// Production
type Service struct { clk clockwork.Clock }
func NewService(clk clockwork.Clock) *Service { return &Service{clk: clk} }
func (s *Service) IsExpired(t time.Time) bool {
return s.clk.Now().After(t)
}
// Test
fc := clockwork.NewFakeClockAt(time.Date(2026, time.January, 1, 0, 0, 0, 0, time.UTC))
svc := NewService(fc)
fc.Advance(time.Hour)
golusoris usage¶
core/clock/—clockwork.Clockprovided via fx (real in production, fake in tests viafxtest).time.Now()is banned outsidecore/clock/; useclk.Now()everywhere.