Run Format

Source file src/pkg/time/tick.go

     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 the
    17	// time with a period specified by the duration argument.
    18	// It adjusts the intervals or drops ticks to make up for slow receivers.
    19	// The duration d must be greater than zero; if not, NewTicker will panic.
    20	func NewTicker(d Duration) *Ticker {
    21		if d <= 0 {
    22			panic(errors.New("non-positive interval for NewTicker"))
    23		}
    24		// Give the channel a 1-element time buffer.
    25		// If the client falls behind while reading, we drop ticks
    26		// on the floor until the client catches up.
    27		c := make(chan Time, 1)
    28		t := &Ticker{
    29			C: c,
    30			r: runtimeTimer{
    31				when:   nano() + int64(d),
    32				period: int64(d),
    33				f:      sendTime,
    34				arg:    c,
    35			},
    36		}
    37		startTimer(&t.r)
    38		return t
    39	}
    40	
    41	// Stop turns off a ticker.  After Stop, no more ticks will be sent.
    42	// Stop does not close the channel, to prevent a read from the channel succeeding
    43	// incorrectly.
    44	func (t *Ticker) Stop() {
    45		stopTimer(&t.r)
    46	}
    47	
    48	// Tick is a convenience wrapper for NewTicker providing access to the ticking
    49	// channel only.  Useful for clients that have no need to shut down the ticker.
    50	func Tick(d Duration) <-chan Time {
    51		if d <= 0 {
    52			return nil
    53		}
    54		return NewTicker(d).C
    55	}

View as plain text