forked from keybase/client
/
bgticker.go
47 lines (39 loc) · 1.04 KB
/
bgticker.go
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
package libkb
import (
"time"
)
const DefaultBgTickerWait = 5 * time.Second
type BgTicker struct {
C <-chan time.Time
c chan time.Time
ticker *time.Ticker
resumeWait time.Duration
}
// This ticker wrap's Go's time.Ticker to wait a given time.Duration before
// firing. This is helpful to not overload the mobile apps when they are
// brought to the foreground and all have tasks that are ready to fire.
// NewBgTicker will panic if wait > duration as time.Ticker does with a
// negative duration.
func NewBgTicker(duration time.Duration) *BgTicker {
return NewBgTickerWithWait(duration, DefaultBgTickerWait)
}
func NewBgTickerWithWait(duration time.Duration, wait time.Duration) *BgTicker {
c := make(chan time.Time, 1)
t := &BgTicker{
C: c,
c: c,
ticker: time.NewTicker(duration - wait),
resumeWait: wait,
}
go t.tick()
return t
}
func (t *BgTicker) tick() {
for c := range t.ticker.C {
time.Sleep(RandomJitter(t.resumeWait))
t.c <- c
}
}
func (t *BgTicker) Stop() {
t.ticker.Stop()
}