time#

time.Duration#

  • time.ParseDuration(s string) (Duration, error)
    • Parses a duration string into a time.Duration.

time.Time#

  • Represents a specific moment in time (time stamp) and includes time zone information.
  • Comparison: Do not use == to check if two time.Time instances refer to the same moment. Instead, use the Equal method, which correctly handles time zones.

Parsing and Formatting#

  • time.Parse(layout, value string) (Time, error)
    • Parses a formatted string into a Time value.
    • The layout defines the format using the reference time: Jan 2 15:04:05 2006 MST ("01/02 03:04:05PM '06 -0700").
  • func (t Time) Format(layout string) string
    • Returns a string representation of the time formatted according to layout.

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: Because time.After(d) discards the *Timer struct and returns only the channel C, it cannot be canceled early or reused. Use timer := 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-select loop, a new time.After(d) countdown starts on every loop iteration. If another case (<-results or <-heartbeat) triggers before d expires, the loop restarts and resets the countdown. Thus, time.After(d) fires only if no other channel activity occurs for duration d.
  • Memory Management: Before Go 1.23, calling time.After(d) inside high-frequency loops leaked underlying timer structs until d expired, requiring explicit timer := time.NewTimer(d) and defer timer.Stop(). Starting in Go 1.23+, unreferenced time.After channels 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#

Featuretime.Ticker (NewTicker(d))time.After(d) (NewTimer(d).C)
Channel Type (C)<-chan time.Time (receive-only)<-chan time.Time (receive-only)
Firing BehaviorRepeats continuously every d (period = d)Fires once after d (period = 0)
Behavior in for-selectTicks at fixed wall-clock intervals (1s, 2s, 3s) even if other cases runResets countdown from 0 whenever another select case executes
Typical RoleCallee / Worker: Emitting periodic heartbeatsCaller / Observer: Detecting inactivity timeouts