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
相關用法
- GO WithDeadline用法及代碼示例
- GO WithValue用法及代碼示例
- 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大神的英文原創作品 WithTimeout。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。