I'm trying to write a select in Go that incorporates an optional timeout, something like this:
done := false
for !done {
if timeout > 0 {
select {
case value := <- somechannel:
// Do something with value
case <- time.After(timeout):
done = true
}
} else {
select {
case value := <- somechannel:
// Do something with value
default:
done = true
}
}
}
That is, if nothing is pending on the channel, and I haven't set a timeout, I exit. If a timeout is set and nothing is available, then I wait for either the timeout or for something to be available on the channel. I'd love to combine this into a single select, but I can't see how I can do that. Any idea?
This is an old question, but since the only answer is poor, I feel like addressing it. The better solution is to use a nil channel, which greatly simplifies the code to not need two separate select statements:
done := false
for !done {
var timerC <-chan time.Time
if timeout > 0 {
timerC = time.After(timeout)
}
select {
case value := <-somechannel:
// Do something with value
case <-timerC:
done = true
}
}
}
A case branch a nil channel will do nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With