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

发布时间 2023-11-21 08:57:41作者: 技术颜良

使用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.")
}
}