英文:
Why won't time.Sleep work in time.Tick?, instead waits 10 seconds
问题
问题1:这是什么原因导致的?
问题2:我需要在每次循环中等待程序执行完毕后再开始重新计算5秒。我该怎么做?
英文:
i have the code:
	n := time.Now()
	i := 0
	for range time.Tick(5 * time.Second) {
		fmt.Printf("start %d %s \n ", i, time.Since(n))
		time.Sleep(10)
		fmt.Printf("end %d %s \n", i, time.Since(n))
		i++
	}
output:
start 0 5.001125s 
 end 0 5.001386916s 
start 1 10.001112041s 
 end 1 10.001232416s 
start 2 15.001064s 
 end 2 15.001094958s 
Trigger every 5 seconds, program execution takes 10 seconds, I found that the sleep method does not take effect, every 5 seconds will automatically print end, no wait 10 seconds.
question:
- 
What is the reason for this?
 - 
I need to wait until the execution of the program in each loop is complete before I start recalculating the 5 seconds. What do I do?
 
答案1
得分: 1
这是原因:
time.Sleep 接受一个 time.Duration 类型的参数,它在内部是一个表示纳秒的 int64 类型。
因此,以下代码会休眠10纳秒:
time.Sleep(10)
要休眠10秒,可以使用预定义的常量之一:
time.Sleep(10*time.Second)
如果你想要在每次循环迭代之间等待至少 5s,那么不要使用 Ticker。Ticker 会在固定的时间间隔上进行循环。以下是一些示例:
- 如果循环任务需要2秒,那么下一次循环迭代将在3秒后开始(5减去2)
 - 如果任务需要8秒(错过了一个 tick),那么迭代之间将没有等待时间;
 - 如果任务需要12秒(错过了2个 tick)- 再次没有等待时间
 
所以,如果你想要确保迭代之间有一致的暂停时间,请在循环结束时加入一个休眠。
英文:
> What is the reason for this?
time.Sleep takes a parameter of type time.Duration which under the covers is an int64 representing nanoseconds.
As a result, this sleeps for 10 nanoseconds:
time.Sleep(10)
To sleep for 10 seconds, use one of the predefined consts:
time.Sleep(10*time.Second)
> I need to wait until the execution of the program in each loop is complete before I start recalculating the 5 seconds
If you want to wait at least 5s between each loop iteration - then don't use a Ticker. A ticker will loop on a regular interval. Some examples:
- if a loop task takes 2s, then the next loop iteration will begin in 3s (5 minus 2)
 - if the task takes 8s (missing a tick), then there will be zero wait between iterations;
 - if the task takes 12s (missing 2 ticks) - again there will be zero wait
 
So if you want to ensure a consistent pause between iterations, put a sleep at the end of the loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论