-
Notifications
You must be signed in to change notification settings - Fork 18.8k
Closed
Labels
Milestone
Description
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.
ainar-g, bcmills, deefdragon and TrevinTeacutteroiooj and TrevinTeacutterainar-g