3 回答

TA貢獻1780條經驗 獲得超5個贊
您可以使用select它來實現(xiàn):
package main
import (
"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")
}

TA貢獻1842條經驗 獲得超21個贊
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:
}
}

TA貢獻1789條經驗 獲得超8個贊
這是一個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())
}
- 3 回答
- 0 關注
- 217 瀏覽
添加回答
舉報