下面的代码:
// Sample program to show how to use the WithDeadline function
// of the Context package.
package main
import (
"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()
慕桂英4014372
函数式编程
相关分类