github.com/amp-space/amp-sdk-go@v0.7.6/stdlib/task/periodic_task.go (about) 1 package task 2 3 import ( 4 "github.com/amp-space/amp-sdk-go/stdlib/utils" 5 ) 6 7 type PeriodicTask struct { 8 Context 9 ticker utils.Ticker 10 mailbox *utils.Mailbox 11 taskFn func(ctx Context) 12 } 13 14 func NewPeriodicTask(name string, ticker utils.Ticker, taskFn func(ctx Context)) *PeriodicTask { 15 return &PeriodicTask{ 16 ticker: ticker, 17 mailbox: utils.NewMailbox(1), 18 taskFn: taskFn, 19 } 20 } 21 22 func (task *PeriodicTask) OnContextStarted(ctx Context, parent Context) error { 23 task.ticker.Start() 24 25 task.Context.Go("ticker", func(ctx Context) { 26 for { 27 select { 28 case <-ctx.Done(): 29 return 30 31 case <-task.ticker.Notify(): 32 task.Enqueue() 33 34 case <-task.mailbox.Notify(): 35 x := task.mailbox.Retrieve() 36 if x != nil { 37 task.taskFn(ctx) 38 } 39 } 40 } 41 }) 42 return nil 43 } 44 45 func (task *PeriodicTask) Close() error { 46 task.ticker.Close() 47 return nil 48 } 49 50 func (task *PeriodicTask) Enqueue() { 51 task.mailbox.Deliver(struct{}{}) 52 }