blob: 4440c2207b33715ce54d087051b10ba5547c6121 [file] [log] [blame]
Russ Coxc7bab462008-12-03 16:40:00 -08001// 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
5package time
6
Russ Cox3b860262011-11-09 15:17:05 -05007import "errors"
Rob Pikefbb70292009-09-23 13:02:14 -07008
9// A Ticker holds a synchronous channel that delivers `ticks' of a clock
10// at intervals.
11type Ticker struct {
Russ Coxefe3d352011-11-30 11:59:44 -050012 C <-chan Time // The channel on which the ticks are delivered.
Russ Cox3b860262011-11-09 15:17:05 -050013 r runtimeTimer
Rob Pikefbb70292009-09-23 13:02:14 -070014}
15
Russ Coxefe3d352011-11-30 11:59:44 -050016// NewTicker returns a new Ticker containing a channel that will send the
17// time, in nanoseconds, 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.
20func NewTicker(d Duration) *Ticker {
21 if d <= 0 {
Russ Coxeb692922011-11-01 22:05:34 -040022 panic(errors.New("non-positive interval for NewTicker"))
Russ Cox6478df12008-12-08 17:45:50 -080023 }
Russ Cox3b860262011-11-09 15:17:05 -050024 // 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.
Russ Coxefe3d352011-11-30 11:59:44 -050027 c := make(chan Time, 1)
Rob Pike2ef09142010-12-13 13:52:19 -080028 t := &Ticker{
Russ Cox3b860262011-11-09 15:17:05 -050029 C: c,
30 r: runtimeTimer{
Russ Coxefe3d352011-11-30 11:59:44 -050031 when: nano() + int64(d),
32 period: int64(d),
Russ Cox3b860262011-11-09 15:17:05 -050033 f: sendTime,
34 arg: c,
35 },
Rob Pike2ef09142010-12-13 13:52:19 -080036 }
Russ Cox3b860262011-11-09 15:17:05 -050037 startTimer(&t.r)
Robert Griesemer45ca9f72009-12-15 15:41:46 -080038 return t
Russ Coxc7bab462008-12-03 16:40:00 -080039}
Russ Cox3b860262011-11-09 15:17:05 -050040
41// Stop turns off a ticker. After Stop, no more ticks will be sent.
42func (t *Ticker) Stop() {
43 stopTimer(&t.r)
44}
45
46// Tick is a convenience wrapper for NewTicker providing access to the ticking
47// channel only. Useful for clients that have no need to shut down the ticker.
Russ Coxefe3d352011-11-30 11:59:44 -050048func Tick(d Duration) <-chan Time {
49 if d <= 0 {
Russ Cox3b860262011-11-09 15:17:05 -050050 return nil
51 }
Russ Coxefe3d352011-11-30 11:59:44 -050052 return NewTicker(d).C
Russ Cox3b860262011-11-09 15:17:05 -050053}