Skip to content

Instantly share code, notes, and snippets.

@alex-leonhardt
Created December 12, 2019 16:21
Show Gist options
  • Save alex-leonhardt/ed7b916a0594bcf265b722387892cbcc to your computer and use it in GitHub Desktop.
Save alex-leonhardt/ed7b916a0594bcf265b722387892cbcc to your computer and use it in GitHub Desktop.
timeout with golang using context.WithTimeout()
package main
import (
"context"
"fmt"
"time"
)
func f(ctx context.Context) {
fmt.Println(time.Now().UTC())
for {
select {
case <-ctx.Done():
fmt.Println(time.Now().UTC())
fmt.Println("i've timed out or what?")
return
default:
fmt.Println(time.Now().UTC())
fmt.Println("still waiting...")
time.Sleep(1 * time.Second)
}
}
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
fmt.Println(time.Now().UTC())
time.Sleep(8 * time.Second)
fmt.Println(time.Now().UTC())
f(ctx)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment