go使用context.withtimtout取消一个超时操作

使用context.WithTimeout

package main

import (
"context"
"fmt"
"time"
)

func main() {
timeout := 5 * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()

done := make(chan bool)

go func() {
    // 模拟耗时操作
    time.Sleep(2 * time.Second)
    done <- true
}()

select {
case <-done:
    fmt.Println("Task completed successfully.")
case <-ctx.Done():
    fmt.Println("Timeout! The operation took too long.")
}
}
posted @   技术颜良  阅读(170)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
历史上的今天:
2022-11-21 三种获取Go项目根目录的方式,让你做架构,选哪种?
2022-11-21 go1.18泛型初体检
2017-11-21 单机安装ELK
点击右上角即可分享
微信分享提示