summaryrefslogtreecommitdiffstats
path: root/src/go/pkg/ticker/ticker.go
blob: e4228fe4c4cbc987e19c074558a75955a6b7186e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// SPDX-License-Identifier: GPL-3.0-or-later

package ticker

import "time"

type (
	// Ticker holds a channel that delivers ticks of a clock at intervals.
	// The ticks are aligned to interval boundaries.
	Ticker struct {
		C        <-chan int
		done     chan struct{}
		loops    int
		interval time.Duration
	}
)

// New returns a new Ticker containing a channel that will send the time with a period specified by the duration argument.
// It adjusts the intervals or drops ticks to make up for slow receivers.
// The duration must be greater than zero; if not, New will panic. Stop the Ticker to release associated resources.
func New(interval time.Duration) *Ticker {
	ticker := &Ticker{
		interval: interval,
		done:     make(chan struct{}, 1),
	}
	ticker.start()
	return ticker
}

func (t *Ticker) start() {
	ch := make(chan int)
	t.C = ch
	go func() {
	LOOP:
		for {
			now := time.Now()
			nextRun := now.Truncate(t.interval).Add(t.interval)

			time.Sleep(nextRun.Sub(now))
			select {
			case <-t.done:
				close(ch)
				break LOOP
			case ch <- t.loops:
				t.loops++
			}
		}
	}()
}

// Stop turns off a Ticker. After Stop, no more ticks will be sent.
// Stop does not close the channel, to prevent a read from the channel succeeding incorrectly.
func (t *Ticker) Stop() {
	t.done <- struct{}{}
}