我將運行一個命令,將輸出推送到檔案系統中的 FIFO 檔案。
在 bash 中,我可以寫入timeout 3000 cat server_fifo>server.url等待,直到 fifo 被推送輸出,或者它達到 3000 超時。
我想知道我們如何在 golang 中做到這一點,即一直等待 fifo 檔案的輸出,并為此等待設定超時。
每matishsiao的要點腳本在這里,我知道我們能做到
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
}
}
但是在這種情況下,如何在 for 回圈中添加超時?
uj5u.com熱心網友回復:
這是您可以使用的簡單樣板:
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")
}
分配time.Second*3或任何Duration給timeout變數。
編輯:添加帶有回呼的示例函式:
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
*/
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352539.html
標籤:走
上一篇:父context.Context與gin.Contect.Request.Context與gin.Context
下一篇:你如何讀取每N位?
