登录
首页 >  Golang >  Go问答

实现循环执行一个函数直到返回 true 或超时的方法

来源:stackoverflow

时间:2024-02-16 23:00:23 308浏览 收藏

大家好,我们又见面了啊~本文《实现循环执行一个函数直到返回 true 或超时的方法》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我有一个函数 checksuccess() ,如果任务完成,它返回 true。

我想每 1 秒调用一次 checksuccess() 并中断,直到返回 true 或超时。

我现在所拥有的是使用 goroutine 运行 for 循环,其中我每 1 秒调用一次 checksuccess() 。在主流程中,我使用 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
}

其实已经达到了我的目的,但是我觉得很乏味。有没有更好(更短)的写法?


正确答案


您不需要单独的 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
           }
      }
   }
}

在这种情况下,我更喜欢使用 context.context,这样实用函数可以更轻松地适应各种现实场景。

我也会返回一些东西,也许是 error,例如来自 ctx.err()bool,向调用者提供一些反馈(调用者可能决定放弃它):

func tryFunc(ctx context.Context, f func() bool) bool {
    ticker := time.NewTicker(time.Second)
    defer ticker.Stop()
    for {
        select {
        case <-ctx.Done():
            return false
        case <-ticker.C:
            if b := f(); b {
                return b
            }
        }
    }
}

演示:https://go.dev/play/p/Iz_urEkBMIi

ps:确保上下文超时。 context.background() 没有

今天关于《实现循环执行一个函数直到返回 true 或超时的方法》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>