1package libkb 2 3import ( 4 "time" 5) 6 7const DefaultBgTickerWait = 5 * time.Second 8 9type BgTicker struct { 10 C <-chan time.Time 11 c chan time.Time 12 ticker *time.Ticker 13 resumeWait time.Duration 14} 15 16// This ticker wrap's Go's time.Ticker to wait a given time.Duration before 17// firing. This is helpful to not overload the mobile apps when they are 18// brought to the foreground and all have tasks that are ready to fire. 19 20// NewBgTicker will panic if wait > duration as time.Ticker does with a 21// negative duration. 22func NewBgTicker(duration time.Duration) *BgTicker { 23 return NewBgTickerWithWait(duration, DefaultBgTickerWait) 24} 25 26func NewBgTickerWithWait(duration time.Duration, wait time.Duration) *BgTicker { 27 c := make(chan time.Time, 1) 28 t := &BgTicker{ 29 C: c, 30 c: c, 31 ticker: time.NewTicker(duration - wait), 32 resumeWait: wait, 33 } 34 go t.tick() 35 return t 36} 37 38func (t *BgTicker) tick() { 39 for c := range t.ticker.C { 40 time.Sleep(RandomJitter(t.resumeWait)) 41 t.c <- c 42 } 43} 44 45func (t *BgTicker) Stop() { 46 t.ticker.Stop() 47} 48