Go 使用context包实现协程的超时控制

2001人浏览 2021-09-18

由于业务需要,部分协程不可能一直执行下去,下面这个简单的方法可以控制协程的运行时长,从而达到超时控制。

//任务处理函数
func doTimeOut(ctx context.Context)  {
	for  {
		//判断超时
		if deadline , ok := ctx.Deadline(); ok {
			if time.Now().After(deadline) {
				fmt.Println(ctx.Err().Error(),"timeout...")
				return
			}
		}
		select {
		//未超时 任务完成
		case <-ctx.Done():
			fmt.Println("done")
			return
		//继续完成任务
		default:
			fmt.Println("work")
		}
		time.Sleep(time.Second * 1)
	}
}


//主函数
func main(){
    //设置五秒超时,可使用WithDeadline(在某个时间点超时)或者WithTimeout(在多少时间后超时)
	//ctx , cancel := context.WithDeadline(context.Background(),time.Now().Add(time.Second * 5))
	ctx , cancel := context.WithTimeout(context.Background(),time.Second * 5)
	defer cancel()
	go doTimeOut(ctx)

	time.Sleep(time.Second * 10)
	return


}

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章