我有一个函数checkSuccess(),如果任务完成则返回 true。
我想checkSuccess()每 1 秒调用一次并中断,直到它返回true或超时。
我现在所拥有的是使用 goroutine 运行 for 循环,其中我checkSuccess()每 1 秒调用一次。在主流程中,我用来time.After检查整个检查持续时间是否已超时。
func myfunc (timeout time.Duration) {
successChan := make(chan struct{})
timeoutChan := make(chan struct{})
// Keep listening to the task.
go func() {
for {
select {
// Exit the forloop if the timeout has been reached
case <-timeoutChan:
return
default:
}
// Early exit if task has succeed.
if checkSuccess() {
close(successChan)
return
}
time.Sleep(time.Second)
}
}()
// Once timeout, stop listening to the task.
select {
case <-time.After(timeout):
close(timeoutChan)
return
case <-successChan:
return
}
return
}
Run Code Online (Sandbox Code Playgroud)
其实已经达到了我的目的,但是我觉得很乏味。有没有更好(更短)的写法?
您不需要单独的 goroutine 或通道:
func myfunc (timeout time.Duration) {
ticker:=time.NewTicker(time.Second)
defer ticker.Close()
to:=time.NewTimer(timeout)
defer to.Stop()
for {
select {
case <-to.C:
return // timeout
case <-ticker:
if checkSuccess() {
return
}
}
}
}
Run Code Online (Sandbox Code Playgroud)