Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Created February 4, 2015 21:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vaskoz/a1c25ce315853aa74471 to your computer and use it in GitHub Desktop.
Save vaskoz/a1c25ce315853aa74471 to your computer and use it in GitHub Desktop.
Use a timeout library to embedded a global timeout within smaller interval timeouts
package main
import (
"fmt"
"github.com/getlantern/withtimeout"
"net/http"
"time"
)
func main() {
ms := 110 // change this to correct number of milliseconds for your connection
intervalDuration, _ := time.ParseDuration(fmt.Sprintf("%dms", ms))
timeoutDuration, _ := time.ParseDuration(fmt.Sprintf("%dms", 10*ms))
interestingFunction := func() (interface{}, error) {
return http.Get("http://google.com")
}
intervaledFunctions := func() (interface{}, error) {
success, failures := 0, 0
for i := 0; i < 10; i++ {
_, t, e := withtimeout.Do(intervalDuration, interestingFunction)
if e == nil {
success += 1
}
if t == true {
failures += 1
}
}
return success, fmt.Errorf("%s", failures)
}
successes, timedout, failures := withtimeout.Do(timeoutDuration, intervaledFunctions)
fmt.Printf("Success: %s, Failures: %s, Timed Out: %s", successes, failures, timedout)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment