2016-06-22 15 views
1
func Tick() {                                   
    fmt.Println("startTime", time.Now().Format("2006-01-02 15:04:05"))                     
    t := time.NewTicker(time.Second * 3)                            
    time.Sleep(time.Second * 12)                              
    for {                                    
     stamp := <-t.C                                 
     fmt.Println("tickTime", stamp.Format("2006-01-02 15:04:05"))                     
    }                                     
}   

Otputである:golang tickerはどのように機能しますか?上記のスニペットから

のstartTime 2016年6月22日16時22分20秒

をtickTime 2016年6月22日夜04時22分23秒

tickTime 2016-06- 22夜四時22分35秒

tickTime 2016年6月22日午後04時22分38秒

tickTime 2016年6月22日夜4時22分41秒

tickTime 2016年6月22日私はティッカーを遅らせる際午後四時22分44秒


は、なぜこれがノータイムスタンプ夜04時22分26秒、午前16時22分二十九秒で起こったのか?

+0

どこを実行していますか?私のためにうまくいくようです:https://play.golang.org/p/3uVTJq9AfN –

+0

@DuruCanCelasunあなたはティッカー期間よりも短い1秒間だけ待っています。 Wait> tick時間が問題になります。 – LinearZoetrope

答えて

6

これは、(私はドキュメントのソースページを、これをオフにコピーし、行番号はご容赦)ティッカーの源である:

func NewTicker(d Duration) *Ticker { 
      if d <= 0 { 
       panic(errors.New("non-positive interval for NewTicker")) 
      } 
      // Give the channel a 1-element time buffer. 
      // If the client falls behind while reading, we drop ticks 
      // on the floor until the client catches up. 
      c := make(chan Time, 1) 
      t := &Ticker{ 
       C: c, 
       r: runtimeTimer{ 
        when: when(d), 
        period: int64(d), 
        f:  sendTime, 
        arg: c, 
       }, 
      } 
      startTimer(&t.r) 
      return t 
     } 

注意何が起こっているコメント

// Give the channel a 1-element time buffer. 
// If the client falls behind while reading, we drop ticks 
// on the floor until the client catches up. 

  1. タイマーを作成する
  2. タイマーで生成されます。最初のダニとそれをバッファリングします。
  3. 今ではそれが2
  4. 結局、あなたのゴルーチンが起動し、すぐにそれが生成された第1 2つのティックを消費し、それが再びダニの生産を開始するダニ生成することができ、あなたが消費するのを待つ、待つ目覚め、およびブロック。

編集:また、(Tickをするための便利な機能です)NewTickerためdocumentionは言う:

NewTickerは、指定された期間で 時間を送信するチャネルを含む新しいティッカーを返します。 duration引数で指定します。それは、遅い受信者を補うために、 間隔を調整したり、ダニを落としたりします。継続時間d はゼロより大きくなければなりません。そうでない場合、NewTickerはパニックに陥ります。関連付けられたリソースを解放するには ティッカーを停止します。

明示的に言及していませんが、バッファーが1のチャネルです。

関連する問題