为了账号安全,请及时绑定邮箱和手机立即绑定

上下文 - WithDeadline() 与 WithTimeout()

上下文 - WithDeadline() 与 WithTimeout()

Go
MMMHUHU 2022-07-11 10:36:56
下面的代码:// Sample program to show how to use the WithDeadline function// of the Context package.package mainimport (    "context"    "fmt"    "time")type data struct {    UserID string}func main() {    // Set a duration.    // duration := 150 * time.Millisecond    duration := time.Now().Add(3 * time.Second)    // Create a context that is both manually cancellable and will signal    // a cancel at the specified duration.    ctx, cancel := context.WithDeadline(context.Background(), duration)    defer cancel()    // Create a channel to received a signal that work is done.    ch := make(chan data, 1)    // Ask the goroutine to do some work for us.    go func() {        // Simulate work.        time.Sleep(50 * time.Millisecond)        // Report the work is done.        ch <- data{"123"}    }()    // Wait for the work to finish. If it takes too long move on.    select {    case d := <-ch:        fmt.Println("work complete", d)    case <-ctx.Done():        fmt.Println("work cancelled")    }}用于WithDeadline发送 timer'd cancel()。这可以使用以下方法完成:duration := 150 * time.Millisecond// Create a context that is both manually cancellable and will signal// a cancel at the specified duration.ctx, cancel := context.WithTimeout(context.Background(), duration)在内部,context.WithTimeout调用该context.WithDeadline函数并通过将超时添加到当前时间来生成截止日期。有多么context.WithTimeout()不同context.WithDeadline()
查看完整描述

2 回答

?
慕桂英4014372

TA贡献1871条经验 获得超13个赞

context.WithTimeout() 与 context.WithDeadline() 有何不同

第一个需要一段持续时间,然后从现在开始取消,第二个是调用取消的绝对时间,如文档中所述,值得像往常一样阅读。


查看完整回答
反对 回复 2022-07-11
?
函数式编程

TA贡献1807条经验 获得超9个赞

WithTimeout是执行的便捷函数WithDeadline(parent, time.Now().Add(timeout))

这些功能在应用程序如何指定截止日期方面有所不同。否则它们是相同的。

调用适合您手头值的函数。


查看完整回答
反对 回复 2022-07-11
  • 2 回答
  • 0 关注
  • 369 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号