英文:
Running a time.Sleep inside a time.Tick does not honour the Sleep period
问题
我很好奇,如果你在time.Tick
内定期运行一个任务,但是任务的执行时间比定时器的时间长会发生什么。
在这里的Playground(https://play.golang.org/p/el7C_bzjpCe)中,等待更长时间以查看输出(即使它显示“timeout”)。
为了模拟任务执行时间较长,我使用了time.Sleep
。令我惊讶的是,当新的time.Tick
到来时,time.Sleep
似乎会自动过期。
问题:
- 有人能解释一下这里的情况吗?
- 如果任务在没有使用
time.Sleep
的情况下确实需要更长时间,当新的time.Tick
到来时,但是之前的任务还没有完成,会发生什么?
英文:
I was curious what happens if you run a task periodically, inside a time.Tick
, but the task is taking longer than the ticker.
Playground here - wait longer to see the output (even though it says "timeout").
In order to simulate that the task is taking longer, I'm using a time.Sleep
. To my surprise, it seems that this time.Sleep
automatically expires when the new time.Tick
comes.
Questions:
- can someone help with an explanation here?
- what if the task is really taking longer without using a time.Sleep? What would happen when the new
time.Tick
comes but the previous task did not finish?
答案1
得分: 4
time.Tick
不会影响 time.Sleep
。
你正在打印计时器的步进时间而不是实际时间。
尝试以下代码:
package main
import (
"fmt"
"time"
)
func main() {
var i int
c := time.Tick(5 * time.Second)
for next := range c {
i++
fmt.Printf("%d) %v\n", i, next)
fmt.Printf("%d) %v\n", i, time.Now())
time.Sleep(8 * time.Second)
fmt.Printf("%d) 睡眠结束\n", i)
}
}
英文:
time.Tick
does not affect time.Sleep
.
You are printing the ticker step time instead of the real time.
Try
package main
import (
"fmt"
"time"
)
func main() {
var i int
c := time.Tick(5 * time.Second)
for next := range c {
i++
fmt.Printf("%d) %v\n", i, next)
fmt.Printf("%d) %v\n", i, time.Now())
time.Sleep(8 * time.Second)
fmt.Printf("%d) finished sleeping\n", i)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论