Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to repetitively run a function until it returns true or timeout?

I have a function checkSuccess() which return true if the task have finished.

I’d like to call checkSuccess() every 1 second and break until it return true or timeout.

What I’m having now is to use a goroutine to run a for loop, in which I call checkSuccess() every 1 second. And in the main process, I use time.After to check if the whole checking duration has passed timeout.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}

It actually has achieved my goal, but I found it very tedious. Is there any better (shorter) way to write it?

>Solution :

You don’t need a separate goroutine or channels:

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
           }
      }
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading