time - 如何仅使用 time.After 编写我自己的 Sleep 函数?

标签 time go sleep channel

我正在尝试使用 Go 中的 time.After 编写自己的 sleep 函数,等同于 time.Sleep

这是代码。第一次尝试:

func Sleep(x int) {
  msg := make(chan int)
  msg := <- time.After(time.Second * x)
}

第二次尝试:

func Sleep(x int) {
 time.After(time.Second * x)
}

两者都返回错误,有人可以向我解释如何使用 time.After 编写等同于 time.Sleep 的 sleep 函数吗?如果可能的话,我什么时候使用 channel ?

最佳答案

time.After()返回给你一个 channel 。在指定的持续时间后,将在 channel 上发送一个值。

所以只需从返回的 channel 接收一个值,接收将阻塞直到发送该值:

func Sleep(x int) {
    <-time.After(time.Second * time.Duration(x))
}

您的错误:

在你的第一个例子中:

msg := <- time.After(time.Second * x)

msg 已经声明,因此 Short variable declaration := 不能使用。接收到的值也将是 time.Time 类型, 所以你甚至不能将它分配给 msg

在你的第二个例子中你需要一个类型 conversion因为 xint 类型,time.Secondtime.Duration 类型,并且 time.After() 需要一个 time.Duration 类型的值。

关于time - 如何仅使用 time.After 编写我自己的 Sleep 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31942163/

相关文章:

java.sql.Date 和 java.sql.Time 到 org.joda.time.DateTime

ruby-on-rails - Rails 时间与 rspec 不一致

linux - golang直接从 block 读取

Bash 日期/时间算法

ruby-on-rails - 日期时间更改 ruby

perl - 两个日期之间的天/月/年

unit-testing - 使用 go test (golang) 查找失败的测试文件名

reactjs - axios.post请求获取404

python - 正确使用PyQt定时器/ sleep

c++ - std::this_thread::sleep_for 时间分辨率