登录
首页 >  Golang >  Go问答

何时执行函数更合适?

来源:stackoverflow

时间:2024-03-07 22:18:23 344浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《何时执行函数更合适?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

用什么比较好? time.afterfunc 还是带有 sleep 的 goroutine?

time.afterfunc(d, func() {
  // things
})
go func() {
  time.Sleep(d)
  // things
}()

正确答案


像大多数计算机科学问题一样 - 答案取决于用法。你的两个选择都会创建一个 goroutine。话虽如此,我会避免使用 time.sleep(),因为它是不间断的。

查看一个人为的轮询服务示例:

func poller(ctx context.context) (err error) {
    for {
        if err = pollrecords(ctx); err != nil {
            return
        }
        time.sleep(1*time.hour) // <- poll interval cannot be interrupted
    }
}

由于 time.sleep 的不间断特性,即使上下文已取消,此函数也可能运行长达一个小时。

要解决此问题,可以使用基于通道的 time.after()

// time.sleep(1*time.hour)

select {
case <-ctx.done():
    return ctx.err() // cancelling the context interrupts the time.after
case <-time.after(1*time.hour):
}

注意time.AfterFunc可以取消 - 但你需要捕获返回的time.timer

t := time.AfterFunc(d, func() {
  // things
})

// ...

t.Stop() // will stop the function firing - if one decides to do so

今天关于《何时执行函数更合适?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>