码迷,mamicode.com
首页 > 其他好文 > 详细

Timers _ golang

时间:2015-03-18 13:53:26      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

We often want to execute Go code at some point in the future, or repeatedly at some interval. Go‘s built-in timer and ticker features make both od these easy. We‘ll look first at timers then tickers

package main

import (
    "fmt"
    "time"
)

func main() {

    timer1 := time.NewTimer(time.Second * 2)

    <-timer1.C
    fmt.Println("Time 1 expired")

    timer2 := time.NewTimer(time.Second)
    go func() {
        <-timer2.C
        fmt.Println("Timer 2 expired")
    }()
    stop2 := timer2.Stop()
    if stop2 {
        fmt.Println("Timer 2 stopped")
    }
}
Time 1 expired
Timer 2 stopped

总结 : 

  1 : <-timer1.C 将导致 block

  2 : If you just wanted to wait, you could have used time.Sleep; You can cancel the timer before it expires 

Timers _ golang

标签:

原文地址:http://www.cnblogs.com/jackkiexu/p/4346904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!