github.com/prebid/prebid-server/v2@v2.18.0/util/task/ticker_task.go (about) 1 package task 2 3 import ( 4 "time" 5 ) 6 7 type Runner interface { 8 Run() error 9 } 10 11 type TickerTask struct { 12 interval time.Duration 13 runner Runner 14 done chan struct{} 15 } 16 17 func NewTickerTask(interval time.Duration, runner Runner) *TickerTask { 18 return &TickerTask{ 19 interval: interval, 20 runner: runner, 21 done: make(chan struct{}), 22 } 23 } 24 25 // Start runs the task immediately and then schedules the task to run periodically 26 // if a positive fetching interval has been specified. 27 func (t *TickerTask) Start() { 28 t.runner.Run() 29 30 if t.interval > 0 { 31 go t.runRecurring() 32 } 33 } 34 35 // Stop stops the periodic task but the task runner maintains state 36 func (t *TickerTask) Stop() { 37 close(t.done) 38 } 39 40 // run creates a ticker that ticks at the specified interval. On each tick, 41 // the task is executed 42 func (t *TickerTask) runRecurring() { 43 ticker := time.NewTicker(t.interval) 44 45 for { 46 select { 47 case <-ticker.C: 48 t.runner.Run() 49 case <-t.done: 50 return 51 } 52 } 53 }