滴答滴答……定时器的使用
package main import (
"fmt"
"time"
)
//定时器的使用
func main() {
t := time.NewTicker(time.Second)
//t.C是个channel,背后是个goroutine
for v := range t.C {
fmt.Println("hello,", v)
}
}
一次定时器
package main import (
"fmt"
"time"
) //定时器的使用
func main() {
select {
//5秒之后触发
case <-time.After(*time.Second):
fmt.Println("after")
}
}
超时控制
package main import (
"fmt"
"time"
) func queryDb(ch chan int) {
time.Sleep(time.Second)
ch <-
}
func main() {
ch := make(chan int)
go queryDb(ch)
t := time.NewTicker(time.Second)
select {
case v := <-ch:
fmt.Println("result", v)
case <-t.C:
fmt.Println("timeout")
}
}
goroutine中使用recover
应用场景,如果某个goroutine panic了,而且这个goroutine里面没有捕获(recover),
那么整个进程就会挂掉。所以好的习惯是每当go产生一个goroutine,就需要写下recover
捕获goroutine的错误
package main import (
"fmt"
"runtime"
"time"
) func test() { defer func() {
if err := recover(); err != nil {
fmt.Println("panic:", err)
}
}() var m map[string]int
m["stu"] =
} func calc() {
for {
fmt.Println("i'm calc")
time.Sleep(time.Second)
}
} func main() {
num := runtime.NumCPU()
runtime.GOMAXPROCS(num - )
go test()
for i := ; i < ; i++ {
go calc()
} time.Sleep(time.Second * )
}