You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
830 B

  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. }