Debian Codegraph @

ticker.go

raw
1 package proton
2
3 import (
4 "math/rand"
5 "time"
6
7 "github.com/ProtonMail/gluon/async"
8 )
9
10 type Ticker struct {
11 C chan time.Time
12
13 stopCh chan struct{}
14 doneCh chan struct{}
15 }
16
17 // NewTicker returns a new ticker that ticks at a random time between period and period+jitter.
18 // It can be stopped by closing calling Stop().
19 func NewTicker(period, jitter time.Duration, panicHandler async.PanicHandler) *Ticker {
20 t := &Ticker{
21 C: make(chan time.Time),
22 stopCh: make(chan struct{}),
23 doneCh: make(chan struct{}),
24 }
25
26 go func() {
27 defer async.HandlePanic(panicHandler)
28
29 defer close(t.doneCh)
30
31 for {
32 select {
33 case <-t.stopCh:
34 return
35
36 case <-time.After(withJitter(period, jitter)):
37 select {
38 case <-t.stopCh:
39 return
40
41 case t.C <- time.Now():
42 // ...
43 }
44 }
45 }
46 }()
47
48 return t
49 }
50
51 func (t *Ticker) Stop() {
52 close(t.stopCh)
53 <-t.doneCh
54 }
55
56 func withJitter(period, jitter time.Duration) time.Duration {
57 if jitter == 0 {
58 return period
59 }
60
61 return period + time.Duration(rand.Int63n(int64(jitter)))
62 }