I have a select block that is listening on 2 channels, a ticker and a timer:
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(5 * time.Second)
for {
select {
case z := <-ticker.C:
fmt.Printf("tick %d
", z)
case <-time.After(12 * time.Second):
fmt.Println("12 seconds elapsed!")
}
}
}
If I run the code, the time.After
case never runs, but the ticker works correctly.
If I remove the ticker, time.After
fires correctly:
package main
import (
"fmt"
"time"
)
func main() {
for {
select {
case <-time.After(12 * time.Second):
fmt.Println("12 seconds elapsed!")
}
}
}
It works correctly if I used a timer rather than time.After
:
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(5 * time.Second)
timer := time.NewTimer(12 * time.Second)
for {
select {
case z := <-ticker.C:
fmt.Printf("tick %d
", z)
case <-timer.C:
fmt.Println("12 seconds elapsed!")
}
}
}
Why does this happen?