Golang 超时控制代码模版


本文摘自网络,作者,侵删。

func main(){
    ctx, cancelFunc := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancelFunc()
    result := make(chan int, 1)
    errChan := make(chan error, 1)
    fmt.Println("start: ", time.Now().Unix())
    select {
    case <-ctx.Done():
        fmt.Println("timeout")
    case result <- process(errChan):
        if len(errChan) > 0 {
            fmt.Println("stop err: ", <-errChan)
            return
        }
        fmt.Println("normal, result: ", <-result)
    case err := <-errChan:
        fmt.Println("err: ", err.Error())
    }
    fmt.Println("end: ", time.Now().Unix())
}
func process(errChan chan error) int {
    // 此处模拟业务逻辑,一定概率报错返回,一定概率正常返回
    rand.Seed(time.Now().UnixNano())
    n := rand.Intn(10)
    fmt.Println(n)
    if n < 5 {
        // 正常返回
        // 此处模拟业务逻辑代码耗费时间
        time.Sleep(3 * time.Second)
    } else {
        errChan <- errors.New("process error")
    }
    return n
}

本文来自:简书

感谢作者:匿名回复123

查看原文:Golang 超时控制代码模版

相关阅读 >>

关于Go值传递和地址传递的例子

ssh连接服务器后执行多条命令

cento8安装Golang及配置

整理在vscode中Go编码发生的问题

Golang chan是否关闭

GoGo语言资料包

Go-array

Go语言中container容器数据结构heap、list、ring

使用cron创建定时任务【Golang 入门系列八】

Golang如何防止意外崩溃

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...