github.com/letsencrypt/go@v0.0.0-20160714163537-4054769a31f6/src/context/withtimeout_test.go (about)

     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  
     5  package context_test
     6  
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"time"
    11  )
    12  
    13  func ExampleWithTimeout() {
    14  	// Pass a context with a timeout to tell a blocking function that it
    15  	// should abandon its work after the timeout elapses.
    16  	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
    17  
    18  	select {
    19  	case <-time.After(1 * time.Second):
    20  		fmt.Println("overslept")
    21  	case <-ctx.Done():
    22  		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
    23  	}
    24  
    25  	// Even though ctx should have expired already, it is good
    26  	// practice to call its cancelation function in any case.
    27  	// Failure to do so may keep the context and its parent alive
    28  	// longer than necessary.
    29  	cancel()
    30  
    31  	// Output:
    32  	// context deadline exceeded
    33  }