| 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 current time on the channel after each tick. The period of the |
| 18 |
// ticks is specified by the duration argument. The ticker will adjust |
| 19 |
// the time 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. The duration d |
| 52 |
// must be greater than zero; if not, Reset will panic. |
| 53 |
func (t *Ticker) Reset(d Duration) { |
| 54 |
if d <= 0 { |
| 55 |
panic("non-positive interval for Ticker.Reset") |
| 56 |
} |
| 57 |
if t.r.f == nil { |
| 58 |
panic("time: Reset called on uninitialized Ticker") |
| 59 |
} |
| 60 |
modTimer(&t.r, when(d), int64(d), t.r.f, t.r.arg, t.r.seq) |
| 61 |
} |
| 62 |
|
| 63 |
// Tick is a convenience wrapper for NewTicker providing access to the ticking |
| 64 |
// channel only. While Tick is useful for clients that have no need to shut down |
| 65 |
// the Ticker, be aware that without a way to shut it down the underlying |
| 66 |
// Ticker cannot be recovered by the garbage collector; it "leaks". |
| 67 |
// Unlike NewTicker, Tick will return nil if d <= 0. |
| 68 |
func Tick(d Duration) <-chan Time { |
| 69 |
if d <= 0 { |
| 70 |
return nil |
| 71 |
} |
| 72 |
return NewTicker(d).C |
| 73 |
} |