GO語言"context"包中"WithDeadline"函數的用法及代碼示例。
用法:
func WithDeadline(parent Context, d time.Time)(Context, CancelFunc)
WithDeadline 返回父上下文的副本,截止日期調整為不遲於 d。如果父節點的截止日期已經早於 d,WithDeadline(parent, d) 在語義上等價於父節點。返回的上下文的 Done 通道在截止日期到期、調用返回的取消函數或父上下文的 Done 通道關閉時關閉,以先發生者為準。
取消此上下文會釋放與其關聯的資源,因此代碼應在此上下文中運行的操作完成後立即調用取消。
例子:
這個例子傳遞了一個帶有任意截止日期的上下文來告訴一個阻塞函數它應該在它到達它時立即放棄它的工作。
package main
import (
"context"
"fmt"
"time"
)
const shortDuration = 1 * time.Millisecond
func main() {
d := time.Now().Add(shortDuration)
ctx, cancel := context.WithDeadline(context.Background(), d)
// Even though ctx will be expired, it is good practice to call its
// cancellation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel()
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
輸出:
context deadline exceeded
相關用法
- GO WithValue用法及代碼示例
- GO WithTimeout用法及代碼示例
- GO WithCancel用法及代碼示例
- GO Writer.Init用法及代碼示例
- GO WordEncoder.Encode用法及代碼示例
- GO WaitGroup用法及代碼示例
- GO WordDecoder.Decode用法及代碼示例
- GO Writer.WriteAll用法及代碼示例
- GO WriteFile用法及代碼示例
- GO WordDecoder.DecodeHeader用法及代碼示例
- GO Writer.RegisterCompressor用法及代碼示例
- GO WalkDir用法及代碼示例
- GO Writer用法及代碼示例
- GO WriteString用法及代碼示例
- GO Write用法及代碼示例
- GO Writer.AvailableBuffer用法及代碼示例
- GO Walk用法及代碼示例
- GO PutUvarint用法及代碼示例
- GO Scanner.Scan用法及代碼示例
- GO LeadingZeros32用法及代碼示例
注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 WithDeadline。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。