Skip to content

Instantly share code, notes, and snippets.

@kelby
Created October 7, 2018 00:32
Show Gist options
  • Save kelby/0bb1023067e7fb19c401b79c3630787e to your computer and use it in GitHub Desktop.
Save kelby/0bb1023067e7fb19c401b79c3630787e to your computer and use it in GitHub Desktop.
Golang 让 for 循环运行一段时间超时自动退出
package main
import (
"fmt"
"time"
)
func main() {
timeout := time.After(time.Second * 10)
finish := make(chan bool)
count := 1
go func() {
for {
select {
case <-timeout:
fmt.Println("timeout")
finish <- true
return
default:
fmt.Printf("haha %d\n", count)
count++
}
time.Sleep(time.Second * 1)
}
}()
<-finish
fmt.Println("Finish")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment