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


GO WithTimeout用法及代碼示例

GO語言"context"包中"WithTimeout"函數的用法及代碼示例。

用法:

func WithTimeout(parent Context, timeout time.Duration)(Context, CancelFunc)

WithTimeout 返回 WithDeadline(parent, time.Now().Add(timeout))。

取消此上下文會釋放與其關聯的資源,因此代碼應在此上下文中運行的操作完成後立即調用取消:

func slowOperationWithTimeout(ctx context.Context) (Result, error) {
	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()  // releases resources if slowOperation completes before timeout elapses
	return slowOperation(ctx)
}

例子:

這個例子傳遞了一個帶有超時的上下文來告訴一個阻塞函數它應該在超時後放棄它的工作。

package main

import (
    "context"
    "fmt"
    "time"
)

const shortDuration = 1 * time.Millisecond

func main() {
    // Pass a context with a timeout to tell a blocking function that it
    // should abandon its work after the timeout elapses.
    ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
    defer cancel()

    select {
    case <-time.After(1 * time.Second):
        fmt.Println("overslept")
    case <-ctx.Done():
        fmt.Println(ctx.Err()) // prints "context deadline exceeded"
    }

}

輸出:

context deadline exceeded

相關用法


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