How do I break out of the idiomatic Go for loop containing select statement, if and only if I receive no signals on any of the channels my select statement is listening to, for a particular period of time.
Let me enhance the question with an example.
Setup:
- Lets say that i have a channel
var listenCh <-chan string
that I am listening to. - Let us assume that some other go routine(not in our control) sends different strings on this channel.
- I do some processing with the given string and then listen for the next string on the
listenCh
.
Requirement:
I want to wait 10 seconds maximum(precision not critical), between two successive signals on the listenCh
, before I shut down my operations(break out of for loop permanently).
Code Stub:
func doingSomething(listenCh <-chan string) {
var mystr string
for {
select {
case mystr <-listenCh:
//dosomething
case /*more than 10 seconds since last signal on listenCh*/:
return
}
}
}
How would I achieve my requirement in the most efficient manner possible.
The usual quit channel technique with time.After(time.Duration)
seems to not reset after one loop and hence the whole program closes in 10 seconds even if there is a continuous stream of values.
I find variants of the question(but not what I want) on SO, but none that I saw answers my particular use case.