withtimeout_test.go 700 B

1234567891011121314151617181920212223242526272829
  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. var workComplete <-chan int
  11. func ExampleWithTimeout() {
  12. // Pass a context with a timeout to tell a blocking function that it
  13. // should abandon its work after the timeout elapses.
  14. ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
  15. select {
  16. case <-workComplete:
  17. cancel()
  18. fmt.Println("overslept")
  19. case <-ctx.Done():
  20. fmt.Println(ctx.Err()) // prints "context deadline exceeded"
  21. }
  22. // Output:
  23. // context deadline exceeded
  24. }