callticker/ticker.go

47 lines
761 B
Go
Raw Normal View History

2024-06-15 12:41:13 -07:00
package callticker
import (
"time"
)
type CallTicker struct {
manualTrigger chan interface{}
2024-06-16 11:35:01 -07:00
function func()
2024-06-15 12:41:13 -07:00
ticker *time.Ticker
duration time.Duration
}
2024-06-16 11:35:01 -07:00
func NewCallTicker(d time.Duration, function func()) *CallTicker {
2024-06-15 12:41:13 -07:00
ticker := &CallTicker{
2024-06-24 15:05:18 -07:00
manualTrigger: make(chan interface{}, 100),
2024-06-15 12:41:13 -07:00
function: function,
ticker: time.NewTicker(d),
duration: d,
}
return ticker
}
func (c *CallTicker) Stop() {
c.ticker.Stop()
}
func (c *CallTicker) Reset(d time.Duration) {
c.ticker.Reset(d)
}
2024-06-17 18:34:23 -07:00
func (c *CallTicker) Force() {
2024-06-15 12:41:13 -07:00
c.manualTrigger <- true
c.Reset(c.duration)
}
func (c *CallTicker) Run() {
for {
select {
case _ = <-c.ticker.C:
c.function()
case _ = <-c.manualTrigger:
c.function()
}
}
}