Select Default and Tickers

Non-blocking Select

Adding a default case to a select statement makes it non-blocking. If no other channel is ready, the default case executes immediately.

select {
case v := <-ch:
    fmt.Println("Received:", v)
default:
    fmt.Println("No data ready, moving on...")
}

Time-based Channels

The time package provides functions that return channels, making them easy to use within select blocks.

  • time.Tick(duration): Returns a channel that sends a value on every interval (e.g., every 500ms).
  • time.After(duration): Returns a channel that sends a single value after the duration has passed. Often used for timeouts.

Example: Polling with Timeout

ticker := time.Tick(1 * time.Second)
stop := time.After(5 * time.Second)

for {
    select {
    case <-ticker:
        fmt.Println("Tick...")
    case <-stop:
        fmt.Println("5 seconds up, stopping!")
        return
    }
}