Created
June 28, 2011 04:24
-
-
Save kylelemons/1050485 to your computer and use it in GitHub Desktop.
Demonstrate timeouts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ for WORKTIME in {1..5}0; do echo -n "$WORKTIME: "; ./timeout --timeout 25 --worktime $WORKTIME; done | |
10: Worker finished | |
20: Worker finished | |
30: Timeout | |
40: Timeout | |
50: Timeout |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"flag" | |
) | |
var ( | |
workerTime = flag.Int64("worktime", 50, "Time for worker to run (ms)") | |
timeout = flag.Int64("timeout", 25, "Timeout (ms)") | |
) | |
func worker(done chan bool) { | |
// simulate long-running computation | |
<-time.After(*workerTime * 1e6) | |
done <- true | |
} | |
func main() { | |
flag.Parse() | |
done := make(chan bool, 1) | |
go worker(done) | |
select { | |
case <-done: | |
fmt.Println("Worker finished") | |
case <-time.After(*timeout * 1e6): | |
fmt.Println("Timeout") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment