Timeouts and Tickers
Using time.After, time.Tick with select
Why timeouts matter
Without timeouts, a goroutine waiting on a slow channel can block forever. The time package provides primitives to add time-based control to channel operations.
time.After for one-shot timeout
time.After(d) returns a channel that receives a value after duration d. Use it in a select case to abort a wait.
select {
case res := <-ch:
fmt.Println(res)
case <-time.After(2 * time.Second):
fmt.Println("timed out")
}All lessons in this course
- The select Statement
- Timeouts and Tickers
- Fan-in and Fan-out Patterns
- Worker Pool Pattern