我用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