I'll run a command that will push output to a FIFO file in the file system.
In bash, I can write timeout 3000 cat server_fifo>server.url
to wait until either the fifo was pushed an output, or it reaches the 3000 timeout.
I wonder how we can do this in golang, i.e. keep waiting for the output of an fifo file, and set a timeout for this wait.
Per matishsiao's gist script here, I know we can do
file, err := os.OpenFile(urlFileName, os.O_CREATE, os.ModeNamedPipe)
if err != nil {
log.Fatal("Open named pipe file error:", err)
}
reader := bufio.NewReader(file)
for {
_, err := reader.ReadBytes('\n')
if err == nil {
fmt.Println("cockroach server started")
break
}
}
But in this case, how to add a time out to the for loop?
CodePudding user response:
This is a simple boilerplate you can use:
finished := make(chan bool)
go func() {
/*
* Place your code here
*/
finished <- true
}()
select {
case <-time.After(timeout):
fmt.Println("Timed out")
case <-finished:
fmt.Println("Successfully executed")
}
Assign time.Second*3
or any Duration
to the timeout
variable.
EDIT: Adding example function with callback:
func timeoutMyFunc(timeout time.Duration, myFunc func()) bool {
finished := make(chan bool)
go func() {
myFunc()
finished <- true
}()
select {
case <-time.After(timeout):
return false
case <-finished:
return true
}
}
func main() {
success := timeoutMyFunc(3*time.Second, func() {
/*
* Place your code here
*/
})
}