src.dualinventive.com/go/dinet/periodic/periodic.go

47 lines
685 B
Go

package periodic
import (
"time"
)
// Periodic item
type Periodic struct {
ticker *time.Ticker
quit chan bool
callback Func
}
// Func type for Periodic callback after every tick
type Func func()
// New create new periodic function callback background goroutine ticker
func New(f Func, d time.Duration) *Periodic {
if f == nil {
return nil
}
p := Periodic{}
p.ticker = time.NewTicker(d)
p.quit = make(chan bool)
p.callback = f
go func() {
for {
select {
case <-p.ticker.C:
p.callback()
case <-p.quit:
p.ticker.Stop()
return
}
}
}()
return &p
}
// Stop signals the periodic goroutine
func (p *Periodic) Stop() {
p.quit <- true
}