Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go计时器实例
Go计时器实例
作者:--    发布时间:2019-11-20

我们经常想在将来的某个时间点执行go代码,或者在某个时间间隔重复执行。 go的内置计时器和自动接收器功能使这两项任务变得容易。我们先看看定时器,然后再看看行情

定时器代表未来的一个事件。可告诉定时器您想要等待多长时间,它提供了一个通道,在当将通知时执行对应程序。在这个示例中,计时器将等待2秒钟。

<-timer1.c阻塞定时器的通道c,直到它发送一个指示定时器超时的值。

如果只是想等待,可以使用time.sleep。定时器可能起作用的一个原因是在定时器到期之前取消定时器。这里有一个例子。

第一个定时器将在启动程序后约2s过期,但第二个定时器应该在它到期之前停止。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

timers.go的完整代码如下所示 -

package main

import "time"
import "fmt"

func main() {

    // timers represent a single event in the future. you
    // tell the timer how long you want to wait, and it
    // provides a channel that will be notified at that
    // time. this timer will wait 2 seconds.
    timer1 := time.newtimer(time.second * 2)

    // the `<-timer1.c` blocks on the timer's channel `c`
    // until it sends a value indicating that the timer
    // expired.
    <-timer1.c
    fmt.println("timer 1 expired")

    // if you just wanted to wait, you could have used
    // `time.sleep`. one reason a timer may be useful is
    // that you can cancel the timer before it expires.
    // here's an example of that.
    timer2 := time.newtimer(time.second)
    go func() {
        <-timer2.c
        fmt.println("timer 2 expired")
    }()
    stop2 := timer2.stop()
    if stop2 {
        fmt.println("timer 2 stopped")
    }
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run timers.go
timer 1 expired
timer 2 stopped

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册