Skip to content

Instantly share code, notes, and snippets.

@kougazhang
Created January 14, 2022 11:07
Show Gist options
  • Save kougazhang/a32878bb09c7eed503d2623b951bc6ea to your computer and use it in GitHub Desktop.
Save kougazhang/a32878bb09c7eed503d2623b951bc6ea to your computer and use it in GitHub Desktop.
#golang #context
package main
import (
"context"
"fmt"
"time"
)
const shortDuration = time.Millisecond
func main() {
d := time.Now().Add(shortDuration)
ctx, cancel := context.WithDeadline(context.Background(), d)
// 即便 ctx 会过期,为了以防万一调用 cancellation 函数也是一个好习惯
// 失败可能会导致 ctx 不过期,这样的话 parent 会比预期时存活更长
defer cancel()
select {
case <-time.After(time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment