duanleixun2439 2018-11-15 09:01
浏览 39
已采纳

两种方式中哪一种是惯用方式? time.Sleep()或股票代码?

I have to execute some statements say every minute. I am not sure which one of the following I should follow. It would be great if someone can explain the pros and cons in terms of memory and CPU.

time.Sleep()

func main() {

go func() {
    for {
        time.Sleep(time.Minute)
        fmt.Println("Hi")
    }
}()

time.Sleep(10 * time.Minute) //just to keep main thread running

}

Or Ticker

func main() {

go func() {
     for _ = range time.Tick(time.Minute) {
      fmt.Println("Hi")
     }

}()

time.Sleep(10 * time.Minute) //just to keep main thread running

}
  • 写回答

2条回答 默认 最新

  • douqian2957 2018-11-15 09:05
    关注

    From the docs:

    NewTicker returns a new Ticker containing a channel that will send the time with a period specified by the duration argument. It adjusts the intervals or drops ticks to make up for slow receivers. The duration d must be greater than zero; if not, NewTicker will panic. Stop the ticker to release associated resources.

    time.Sleep just waits for the provided time and continues with the program. There is no adjustment if the rest of the code takes longer.

    The ticker takes the execution time of the provided block into account and skips an interval, if necessary.

    Imagine this scenario: You provide an interval of one minute and your code takes 10 seconds to execute.

    In your first version your program executes your code for ten seconds and then sleeps for 60 seconds. Practically it gets called every 70 seconds.

    In your second version your code gets executed for 10 seconds, then the ticker adjusts the wait time to 50 seconds. Your code gets executed exactly each minute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接