Black Lives Matter. Support the Equal Justice Initiative.

Source file src/time/tick.go

Documentation: time

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package time
     6  
     7  import "errors"
     8  
     9  // A Ticker holds a channel that delivers ``ticks'' of a clock
    10  // at intervals.
    11  type Ticker struct {
    12  	C <-chan Time // The channel on which the ticks are delivered.
    13  	r runtimeTimer
    14  }
    15  
    16  // NewTicker returns a new Ticker containing a channel that will send
    17  // the time on the channel after each tick. The period of the ticks is
    18  // specified by the duration argument. The ticker will adjust the time
    19  // interval or drop ticks to make up for slow receivers.
    20  // The duration d must be greater than zero; if not, NewTicker will
    21  // panic. Stop the ticker to release associated resources.
    22  func NewTicker(d Duration) *Ticker {
    23  	if d <= 0 {
    24  		panic(errors.New("non-positive interval for NewTicker"))
    25  	}
    26  	// Give the channel a 1-element time buffer.
    27  	// If the client falls behind while reading, we drop ticks
    28  	// on the floor until the client catches up.
    29  	c := make(chan Time, 1)
    30  	t := &Ticker{
    31  		C: c,
    32  		r: runtimeTimer{
    33  			when:   when(d),
    34  			period: int64(d),
    35  			f:      sendTime,
    36  			arg:    c,
    37  		},
    38  	}
    39  	startTimer(&t.r)
    40  	return t
    41  }
    42  
    43  // Stop turns off a ticker. After Stop, no more ticks will be sent.
    44  // Stop does not close the channel, to prevent a concurrent goroutine
    45  // reading from the channel from seeing an erroneous "tick".
    46  func (t *Ticker) Stop() {
    47  	stopTimer(&t.r)
    48  }
    49  
    50  // Reset stops a ticker and resets its period to the specified duration.
    51  // The next tick will arrive after the new period elapses.
    52  func (t *Ticker) Reset(d Duration) {
    53  	if t.r.f == nil {
    54  		panic("time: Reset called on uninitialized Ticker")
    55  	}
    56  	modTimer(&t.r, when(d), int64(d), t.r.f, t.r.arg, t.r.seq)
    57  }
    58  
    59  // Tick is a convenience wrapper for NewTicker providing access to the ticking
    60  // channel only. While Tick is useful for clients that have no need to shut down
    61  // the Ticker, be aware that without a way to shut it down the underlying
    62  // Ticker cannot be recovered by the garbage collector; it "leaks".
    63  // Unlike NewTicker, Tick will return nil if d <= 0.
    64  func Tick(d Duration) <-chan Time {
    65  	if d <= 0 {
    66  		return nil
    67  	}
    68  	return NewTicker(d).C
    69  }
    70  

View as plain text