我有一个关于调度"可取消"gorouting的基本问题.
我想每3秒安排一次函数执行.
该功能最多需要5秒钟.
如果需要2999毫秒以上,我想停止/终止它,以避免与下一个重叠.
我做错了:
func main() {
fmt.Println("开始处理")
go 开始处理()
time.Sleep(time.Second * 60)
fmt.Println("endProcessing after 60s")
}
func 开始处理() {
ticker := time.NewTicker(3 * time.Second)
for _ = range ticker.C {
ctx, _ := context.WithTimeout(context.Background(), (time.Second*3)-time.Millisecond)
fmt.Println("开始剂量测量")
doSomething(ctx)
}
}
func doSomething(ctx context.Context) {
executionTime := time.Duration(rand.Intn(5)+1) * time.Second
for {
select {
case <-ctx.Done():
fmt.Printf("timed out after %s\n", executionTime)
return
default:
time.Sleep(executionTime)
fmt.Printf("did something in %s\n", executionTime)
return
}
}
}
这是我现在的输出:
开始处理
开始剂量测量
在2s中做了些什么
开始剂量测量
在3秒内做了些什么
开始剂量测量
在3秒内做了些什么
开始剂量测量
在5s内做了一些事情
开始剂量测量
在2s中做了些什么
...
I want to read timed out after 5s
instead of 在5s内做了一些事情
.