Golang之定时器,recover

滴答滴答……定时器的使用

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(5*time.Second):
        fmt.Println("after")
    }
}

超时控制

package main

import (
    "fmt"
    "time"
)

func queryDb(ch chan int) {
    time.Sleep(time.Second)
    ch <- 100
}
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"] = 100
}

func calc() {
    for {
        fmt.Println("i'm calc")
        time.Sleep(time.Second)
    }
}

func main() {
    num := runtime.NumCPU()
    runtime.GOMAXPROCS(num - 1)
    go test()
    for i := 0; i < 2; i++ {
        go calc()
    }

    time.Sleep(time.Second * 10000)
}

 

posted @ 2018-01-22 18:36  py鱼  阅读(568)  评论(0编辑  收藏  举报
点我回主页