tick.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. package time
  5. import "errors"
  6. // A Ticker holds a channel that delivers `ticks' of a clock
  7. // at intervals.
  8. type Ticker struct {
  9. C <-chan Time // The channel on which the ticks are delivered.
  10. r runtimeTimer
  11. }
  12. // NewTicker returns a new Ticker containing a channel that will send the
  13. // time with a period specified by the duration argument.
  14. // It adjusts the intervals or drops ticks to make up for slow receivers.
  15. // The duration d must be greater than zero; if not, NewTicker will panic.
  16. // Stop the ticker to release associated resources.
  17. func NewTicker(d Duration) *Ticker {
  18. if d <= 0 {
  19. panic(errors.New("non-positive interval for NewTicker"))
  20. }
  21. // Give the channel a 1-element time buffer.
  22. // If the client falls behind while reading, we drop ticks
  23. // on the floor until the client catches up.
  24. c := make(chan Time, 1)
  25. t := &Ticker{
  26. C: c,
  27. r: runtimeTimer{
  28. when: when(d),
  29. period: int64(d),
  30. f: sendTime,
  31. arg: c,
  32. },
  33. }
  34. startTimer(&t.r)
  35. return t
  36. }
  37. // Stop turns off a ticker. After Stop, no more ticks will be sent.
  38. // Stop does not close the channel, to prevent a read from the channel succeeding
  39. // incorrectly.
  40. func (t *Ticker) Stop() {
  41. stopTimer(&t.r)
  42. }
  43. // Tick is a convenience wrapper for NewTicker providing access to the ticking
  44. // channel only. Useful for clients that have no need to shut down the ticker.
  45. func Tick(d Duration) <-chan Time {
  46. if d <= 0 {
  47. return nil
  48. }
  49. return NewTicker(d).C
  50. }