当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。