From b1de6c9246670d764759c48033ed84bcd6101aa4 Mon Sep 17 00:00:00 2001 From: dave Date: Sat, 15 Jun 2024 12:41:13 -0700 Subject: [PATCH] initial commit --- go.mod | 3 +++ ticker.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 go.mod create mode 100644 ticker.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..251a818 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.davepedu.com/dave/callticker + +go 1.22.0 diff --git a/ticker.go b/ticker.go new file mode 100644 index 0000000..30d90fc --- /dev/null +++ b/ticker.go @@ -0,0 +1,46 @@ +package callticker + +import ( + "time" +) + +type CallTicker struct { + manualTrigger chan interface{} + function func(...interface{}) interface{} + ticker *time.Ticker + duration time.Duration +} + +func NewCallTicker(d time.Duration, function func(...interface{}) interface{}) *CallTicker { + ticker := &CallTicker{ + manualTrigger: make(chan interface{}), + 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) +} + +func (c *CallTicker) Trigger() { + c.manualTrigger <- true + c.Reset(c.duration) +} + +func (c *CallTicker) Run() { + for { + select { + case _ = <-c.ticker.C: + c.function() + case _ = <-c.manualTrigger: + c.function() + } + } +}