Skip to content

proposal: time: context-aware time Ticker and Timer #45571

@alercah

Description

@alercah

Currently, time.Ticker and time.Timer are not context-aware. A typical context-aware usage of a time.Ticker might look like this:

ticker := time.NewTicker(time.Second)
defer ticker.Stop()

for {
  select {
    case val := <-ticker.C:
      // Do things
    case <-ctx.Done():
      return ctx.Err()
  }
}

But it could look like this:

ticker := time.NewTickerCtx(ctx, time.Second)
for val := range <-ticker.C {
  // Do things
}

The context-aware Timer and Ticker would automatically stop and close the channel when the context is cancelled. The channel must be closed, unlike with Stop(), or else the client would still need to check for the context being cancelled. With cancellation via select, there is no risk of a spurious last tick as there is with Stop(). For consistency, I propose that Stop() should retain its existing behaviour, even for timers/tickers created with NewTimerCtx/NewTickerCtx.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions