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

}

图片转代码服务由CSDN问答提供 功能建议

我必须每分钟执行一些语句。 我不确定应该遵循以下哪一项。 如果有人可以在内存和CPU方面说明优缺点,那就太好了。

time.Sleep()

  func main(){
 
go func(){
 for {
 time.Sleep(time.Minute)
 fmt.Println(“ H​​i”)
} 
}(  )
 
time.Sleep(10 * time.Minute)//只是保持主线程运行
 
} 
   
 
 

Or Ticker < / strong>

  func main(){
 
go func(){
 for _ = range time.Tick(time.Minute){
 fmt.Println  (“ Hi”)
} 
 
}()
 
time.Sleep(10 * time.Minute)//只是保持主线程运行
 
} 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 评论
  • duanchijie2323 2018-11-15 09:09

    In the example above there is no difference. But ticker also concurrent safe since it uses channels. For example you can create few workers that should make some job every 2 seconds and you need 1 worker make this work at same time, than you use ticker.

    点赞 评论

相关推荐 更多相似问题