Skip to content

Instantly share code, notes, and snippets.

@PatrickGopher
Created July 3, 2020 04:02
Show Gist options
  • Save PatrickGopher/9a9e5d2021a39714967d8539382fb9c5 to your computer and use it in GitHub Desktop.
Save PatrickGopher/9a9e5d2021a39714967d8539382fb9c5 to your computer and use it in GitHub Desktop.
go context WithDeadline demo
func delay(ctx context.Context, t int) {
go func() {
for {
time.Sleep(2 * time.Second)
fmt.Println("running ... ")
}
}()
select {
case <-ctx.Done():
fmt.Println("delay() Done:", ctx.Err())
return
case r := <-time.After(time.Duration(t) * time.Second):
fmt.Println("delay():", r)
}
return
}
func main() {
ctx := context.Background()
deadline := time.Now().Add(time.Duration(10) * time.Second)
ctx, cancel := context.WithDeadline(ctx, deadline)
defer cancel()
delay(ctx, 5)
time.Sleep(10 * time.Second)
cancel()
}
//output:
running ...
running ...
delay(): 2020-07-03 12:01:17.004694 +0800 +08 m=+5.004334114
running ...
running ...
running ...
running ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment