time#
time.Duration#
time.ParseDuration(s string) (Duration, error)- Parses a duration string into a
time.Duration.
- Parses a duration string into a
time.Time#
- Represents a specific moment in time (time stamp) and includes time zone information.
- Comparison: Do not use
==to check if twotime.Timeinstances refer to the same moment. Instead, use theEqualmethod, which correctly handles time zones.
Parsing and Formatting#
time.Parse(layout, value string) (Time, error)- Parses a formatted string into a
Timevalue. - The
layoutdefines the format using the reference time:Jan 2 15:04:05 2006 MST("01/02 03:04:05PM '06 -0700").
- Parses a formatted string into a
func (t Time) Format(layout string) string- Returns a string representation of the time formatted according to
layout.
- Returns a string representation of the time formatted according to
Timers and Tickers#
Go provides two distinct primitives for scheduling time-based events over channels: Timers (one-shot countdowns) and Tickers (repeating metronomes). Both expose a receive-only channel of type <-chan time.Time that delivers the exact time.Time timestamp when fired, and both share the same underlying Go runtime timer engine (period = 0 for Timer vs period = d for Ticker).
type Timer struct {
C <-chan Time // Receive-only channel prevents external close() or fake writes
}
type Ticker struct {
C <-chan Time // Delivers the exact time.Time of each tick
}time.Timer vs time.After (One-Shot Countdown)#
time.After(d Duration) <-chan Time is a 1-line helper (return NewTimer(d).C) that waits for duration d and sends the current time.Time once on the returned channel.
- When to use
time.NewTimer(d)directly: Becausetime.After(d)discards the*Timerstruct and returns only the channelC, it cannot be canceled early or reused. Usetimer := time.NewTimer(d)when you need.Stop()(to cancel before firing and free resources immediately) or.Reset(d)(to reuse the timer instance). - Use Case (Inactivity Watchdog): Placed inside a
for-selectloop, a newtime.After(d)countdown starts on every loop iteration. If another case (<-resultsor<-heartbeat) triggers beforedexpires, the loop restarts and resets the countdown. Thus,time.After(d)fires only if no other channel activity occurs for durationd. - Memory Management: Before Go 1.23, calling
time.After(d)inside high-frequency loops leaked underlying timer structs untildexpired, requiring explicittimer := time.NewTimer(d)anddefer timer.Stop(). Starting in Go 1.23+, unreferencedtime.Afterchannels are immediately garbage-collected by the runtime.
for {
select {
case msg := <-workStream:
process(msg)
case timeoutAt := <-time.After(2 * time.Second):
// Fires ONLY if 2 full seconds pass without receiving from workStream
return fmt.Errorf("inactivity timeout at %v", timeoutAt)
}
}time.Ticker (Repeating Interval)#
time.NewTicker(d Duration) *Ticker returns a struct containing C <-chan Time that delivers time.Time values repeatedly at fixed wall-clock intervals of duration d.
- Use Case (Periodic Emission): Used by workers or background tasks that must emit periodic signals (eg. sending heartbeat pulses or flushing metrics every second) regardless of other channel activity.
- Resource Cleanup: Always call
defer ticker.Stop()to release associated runtime resources when the goroutine exits.
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case tickTime := <-ticker.C:
emitHeartbeat(tickTime)
}
}Comparison: time.Ticker vs time.After#
| Feature | time.Ticker (NewTicker(d)) | time.After(d) (NewTimer(d).C) |
|---|---|---|
Channel Type (C) | <-chan time.Time (receive-only) | <-chan time.Time (receive-only) |
| Firing Behavior | Repeats continuously every d (period = d) | Fires once after d (period = 0) |
Behavior in for-select | Ticks at fixed wall-clock intervals (1s, 2s, 3s) even if other cases run | Resets countdown from 0 whenever another select case executes |
| Typical Role | Callee / Worker: Emitting periodic heartbeats | Caller / Observer: Detecting inactivity timeouts |