我用Go編寫了一個長時間運行的服務器。主程序會執行程序邏輯的幾個例程。之後,主沒有任何用處。一旦主要退出,程序將退出。我現在用來保持程序運行的方法只是對fmt.Scanln()的簡單調用。我想知道其他人如何避免主要退出。以下是一個基本的例子。這裏可以使用什麼想法或最佳實踐?如何保持長時間運行的Go程序,運行?
我考慮創建一個頻道,並通過在所述頻道上接收延遲主體退出,但是我認爲如果我的所有goroutine在某個時間點變得無效,可能會有問題。注意:在我的服務器(不是例子)中,程序實際上並沒有連接到一個shell,因此無論如何與控制檯交互都沒有意義。目前它可行,但我正在尋找「正確」的方式,假設有一個。
package main
import (
"fmt"
"time"
)
func main() {
go forever()
//Keep this goroutine from exiting
//so that the program doesn't end.
//This is the focus of my question.
fmt.Scanln()
}
func forever() {
for ; ; {
//An example goroutine that might run
//indefinitely. In actual implementation
//it might block on a chanel receive instead
//of time.Sleep for example.
fmt.Printf("%v+\n", time.Now())
time.Sleep(time.Second)
}
}
例子,我發現6種方法,使其 - HTTP:// pliutau。com/different-ways-block-go-runtime-forever/ – pltvs 2017-04-25 01:40:05