在 time.Tick 内部运行 time.Sleep 不会遵守 Sleep 的时间间隔。

huangapple go评论90阅读模式
英文:

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似乎会自动过期。

问题:

  1. 有人能解释一下这里的情况吗?
  2. 如果任务在没有使用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:

  1. can someone help with an explanation here?
  2. 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)
	}
}

huangapple
  • 本文由 发表于 2021年11月15日 18:14:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/69972711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定