當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO WithDeadline用法及代碼示例

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

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 WithDeadline。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。