依赖轮询器一直运行的Go应用,保证其稳定性的建议

标签 go scheduler goroutine ticker stability

所以我的应用程序依赖于每 x 秒轮询一次的 goroutine。

func main() {
   // ...
   go p.StartPoller();
}

有哪些提示可确保此轮询器始终运行?

我只是厌倦了一些事情,也许是因为我没有完全理解 go 中错误捕获的概念。由于错误是值,并且假设我没有或我使用的任何库调用 panic(),并且没有空指针引用或数组越界此 goroutine 内的任何代码都不应使 goroutine 正确崩溃?

func (p *Poller) StartPoller() {
        ticker := time.NewTicker(3 * time.Second)
        defer ticker.Stop() 

        for {
            <-ticker.C
            // code here
        }

    }

最佳答案

你是对的,你发布的代码不应该崩溃并因此“崩溃”goroutine。

作为最佳实践,要确保 //code here 也不会这样做,请将其“包装”在函数(匿名或命名函数)中,然后使用 recover( )(延迟!)。这将确保轮询任务也永远不会“崩溃”轮询调度程序。

像这样:

func (p *Poller) StartPoller() {
    ticker := time.NewTicker(3 * time.Second)
    defer ticker.Stop()

    for {
        <-ticker.C

        func() {
            defer func() {
                if r := recover(); r != nil {
                    fmt.Println("Recovered: %v", r)
                }
            }()

            // code here
            // If this would panic, it will be recovered...
        }()
    }
}

即使轮询器要一直运行,我仍然会向它添加一个“关闭” channel ,以提供优雅终止的可能性:

func (p *Poller) StartPoller(shutdown <-chan struct{}) {
    ticker := time.NewTicker(3 * time.Second)
    defer ticker.Stop()

    for {
        select {
        case <-ticker.C:
        case <-shutdown:
            return
        }

        func() {
            defer func() {
                if r := recover(); r != nil {
                    fmt.Println("Recovered: %v", r)
                }
            }()

            // code here
            // If this would panic, it will be recovered...
        }()
    }
}

关于依赖轮询器一直运行的Go应用,保证其稳定性的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026549/

相关文章:

go - 如何确保代码在 Go 中没有数据竞争?

multithreading - 你会如何定义一个 goroutines 池来一次执行?

go - 如何使用 go 服务(正确地)一个 react-router?

go - 直接从一个 channel 发送到另一个 channel

gdb - Go:使用 gdb 打印变量

ruby - 在 ruby​​ 脚本中使用 rufus scheduler

arrays - Golang解码字符串数组

linux - 在linux task scheduler中,周期性调用什么函数来做调度工作?

MYSQL 在事件调度程序中使用事务

multithreading - Goroutines - 为什么我只在最后看到并排执行