Go計時器實例

我們經常想在將來的某個時間點執行Go代碼,或者在某個時間間隔重複執行。 Go的內置計時器和自動接收器功能使這兩項任務變得容易。我們先看看定時器,然後再看看行情。

定時器代表未來的一個事件。可告訴定時器您想要等待多長時間,它提供了一個通道,在當將通知時執行對應程序。在這個示例中,計時器將等待2秒鐘。

<-timer1.C阻塞定時器的通道C,直到它發送一個指示定時器超時的值。

如果只是想等待,可以使用time.Sleep。定時器可能起作用的一個原因是在定時器到期之前取消定時器。這裏有一個例子。

第一個定時器將在啓動程序後約2s過期,但第二個定時器應該在它到期之前停止。

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.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