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

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  /*
    10  	超时取消任务并返回
    11  	能基于某个时间点计时 超时timeout 就快速取消任务并返回
    12  */
    13  const shortDuration = 1 * time.Millisecond // a reasonable duration to block in an example
    14  
    15  func main() {
    16  	// WithDeadline 是基于某个时间点开始计时 超时
    17  	d := time.Now().Add(shortDuration)
    18  	ctx, cancel := context.WithDeadline(context.Background(), d)
    19  	// 建议手动再次cancel
    20  	defer cancel()
    21  	select {
    22  	case <-time.After(1 * time.Second):
    23  		fmt.Println("finsihed with timeout")
    24  	case <-ctx.Done():
    25  		fmt.Println("finished with deadline expired")
    26  		// deadline 会有错误说明
    27  		fmt.Println(ctx.Err())
    28  	}
    29  }
    30  
    31  //finished with deadline expired
    32  // context deadline exceeded