当前位置: 首页 > news >正文

golang context.WithTimeout - running

golang context.WithTimeout

 

go context 超时控制实例

package mainimport ("context""fmt""time"
)func operation(ctx context.Context) (string, error) {cha := make(chan string)go func() {// 模拟执行实际业务处理time.Sleep(time.Second * 10)//业务处理结束//处理成功之后发送hellocha <- "hello"}()for {select {//监听超时通道case <-ctx.Done():fmt.Println("timeSleep cancelled")return "", ctx.Err()//监听任务完成通道case res := <-cha:fmt.Printf(" handl success %s ", res)return res, nil}}
}func main() {ctx := context.Background()ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()res, err := operation(ctx)if err != nil {fmt.Printf("处理失败 %s \n", err)} else {fmt.Printf("处理成功 %s \n", res)}time.Sleep(5 * time.Minute)
}