Even @ Ainar-G already provided the answer, another possibility is to use time.Tick(1e9) to generate a timestamp every second, and then listen to timeAfter after the specified period.
package main import ( "fmt" "time" ) func main() { count := 0 timeTick := time.Tick(1 * time.Second) timeAfter := time.After(5 * time.Second) for { select { case <-timeTick: count++ fmt.Printf("tick %d\n", count) if count >= 5 { fmt.Printf("ugh\n") return } case <-timeAfter: fmt.Printf("timeout\n") return } } }
source share