Skip to content

Instantly share code, notes, and snippets.

@piotrpersona
Created January 22, 2022 09:39
Show Gist options
  • Save piotrpersona/d001daec1a798fcf8911a80c191d520a to your computer and use it in GitHub Desktop.
Save piotrpersona/d001daec1a798fcf8911a80c191d520a to your computer and use it in GitHub Desktop.
Go context with timeout: https://goplay.space/#oPYIR4Y3xAM
package main
import (
"context"
"fmt"
"time"
)
func ctxSafe(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("context done")
return
default:
time.Sleep(time.Second)
fmt.Printf("handling %s\n", time.Now().String())
}
}
}
func notSafe(ctx context.Context) {
fmt.Println("before")
ctxSafe(ctx)
fmt.Println("after")
}
func main() {
ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
notSafe(ctx)
}
// T+00.000000before
// T+01.000000handling 2009-11-10 23:00:01 +0000 UTC m=+1.000000001
// T+02.000000handling 2009-11-10 23:00:02 +0000 UTC m=+2.000000001
// T+03.000000handling 2009-11-10 23:00:03 +0000 UTC m=+3.000000001
// context done
// after
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment