github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/coding/context/WithTimeout.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  /*
    10  	需求: 基于现在计时,超时timeout 就快速取消任务并返回
    11  	如果是基于现在计时,则建议优先使用WithTimeout
    12  	因为WithTimeout 源码也是调用的WithDeadline
    13  */
    14  const shortDuration = 1 * time.Millisecond // a reasonable duration to block in an example
    15  
    16  func main() {
    17  	ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
    18  	defer cancel()
    19  
    20  	select {
    21  	case <-time.After(1 * time.Second):
    22  		fmt.Println("finished with expired")
    23  	case <-ctx.Done():
    24  		fmt.Println("finished with timeout")
    25  		// timeout 之后 会有err 说明
    26  		// 这个err 和WithDeadline 的err一样
    27  		// 因为WithTimeout底层调用的就是WithDeadline
    28  		fmt.Println(ctx.Err())
    29  	}
    30  }
    31  
    32  // finished with timeout
    33  // context deadline exceeded