From 2a82e2a75e53fec9002132d51dc9b72fcce335fb Mon Sep 17 00:00:00 2001 From: Christian Rocha Date: Mon, 11 May 2020 13:01:42 -0400 Subject: [PATCH] Add Tick to run timers independent of the system clock --- subscriptions.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/subscriptions.go b/subscriptions.go index 9c4e95e..cd5fa46 100644 --- a/subscriptions.go +++ b/subscriptions.go @@ -9,9 +9,10 @@ import ( type NewEveryMsg func(time.Time) Msg // Every is a subscription that ticks with the system clock at the given -// duration. +// duration, similar to cron. It's particularly useful if you have several +// subscriptions that need to run in sync. // -// TODO: make it cancelable +// TODO: make it cancelable. func Every(duration time.Duration, newMsg NewEveryMsg) Sub { return func() Msg { n := time.Now() @@ -23,3 +24,17 @@ func Every(duration time.Duration, newMsg NewEveryMsg) Sub { } } } + +// Tick is a subscription that at an interval independent of the system clock +// at the given duration. That is, it begins precisely when invoked. +// +// TODO: make it cancelable. +func Tick(d time.Duration, newMsg NewEveryMsg) Sub { + return func() Msg { + t := time.NewTimer(d) + select { + case now := <-t.C: + return newMsg(now) + } + } +}