-
翻阅古今
您可以使用select它来实现:package mainimport ( "fmt" "time" "context")func main() { fmt.Println("Hello, playground") ctx, cancel := context.WithCancel(context.Background()) defer cancel() go func(){ t := time.Now() select{ case <-ctx.Done(): //context cancelled case <-time.After(2 * time.Second): //timeout } fmt.Printf("here after: %v\n", time.Since(t)) }() cancel() //cancel manually, comment out to see timeout kick in time.Sleep(3 * time.Second) fmt.Println("done")}这是Go-playground 链接
-
茅侃侃
select您可以像其他人提到的那样使用;但是,其他答案有一个错误,因为timer.After()如果不清理就会泄漏内存。func SleepWithContext(ctx context.Context, d time.Duration) { timer := time.NewTimer(d) select { case <-ctx.Done(): if !timer.Stop() { <-timer.C } case <-timer.C: }}
-
拉丁的传说
这是一个sleepContext您可以用来代替的函数time.Sleep:func sleepContext(ctx context.Context, delay time.Duration) { select { case <-ctx.Done(): case <-time.After(delay): }}以及一些示例用法(Go Playground 上的完整可运行代码):func main() { ctx := context.Background() fmt.Println(time.Now()) sleepContext(ctx, 1*time.Second) fmt.Println(time.Now()) ctxTimeout, cancel := context.WithTimeout(ctx, 500*time.Millisecond) sleepContext(ctxTimeout, 1*time.Second) cancel() fmt.Println(time.Now())}