go from the beginning of the language examples Example31. Timer

We frequently need a time code after the Go or repeated operation within a certain time interval.

Go's built-  timers  and  RBI  characteristics make these easy to implement. We will learn first timer, then learn RBI .

Example:

main Package Penalty for
 Import  " fmt " 
Import  " Time " 


FUNC main () {
     // timer represents an independent event at a future point in time.
    // You need a timer to tell the waiting time, then it will provide a channel for notification.
    // timers here will wait 2 seconds. 
    timer1: = time.NewTimer (time.Second * 2 )

     // <- timer1.C until this timer channel C clear before sending a timer failure, would have been blocked.
    <- timer1.C 
    fmt.Println ( " . The Timer expired The 1 " )

     // If you just need a simple wait, you need to use time.Sleep.
    // timer is useful for one of the reasons is that you can before the timer failure to cancel the timer. This is an example 
    Timer2: =  time.NewTimer (time.Second)
    Go FUNC () {
         <- timer2.C 
        fmt.Println ( " the Timer expired The 2. " ) 
    } ()

     // stop the timer. 
    STOP2: = timer2.Stop ()
     IF STOP2 { 
        fmt.Println ( " the Timer 2 STOP. " ) 
    } 
}

Result:

$go run example.go
Timer 1 expired.
Timer 2 stop.
The first timer will start after the program ~ 2S fail, but the second did not fail before it stopped.

Guess you like

Origin www.cnblogs.com/yhleng/p/11757002.html