3 使用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.")
}
}
标签:fmt,cancel,done,context,time,go,withtimtout
From: https://www.cnblogs.com/cheyunhua/p/17845451.html