withtimeout_test.go 830 B

12345678910111213141516171819202122232425262728293031
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package context_test
  5. import (
  6. "fmt"
  7. "time"
  8. "golang.org/x/net/context"
  9. )
  10. // This example passes a context with a timeout to tell a blocking function that
  11. // it should abandon its work after the timeout elapses.
  12. func ExampleWithTimeout() {
  13. // Pass a context with a timeout to tell a blocking function that it
  14. // should abandon its work after the timeout elapses.
  15. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  16. defer cancel()
  17. select {
  18. case <-time.After(1 * time.Second):
  19. fmt.Println("overslept")
  20. case <-ctx.Done():
  21. fmt.Println(ctx.Err()) // prints "context deadline exceeded"
  22. }
  23. // Output:
  24. // context deadline exceeded
  25. }