Add Tick to run timers independent of the system clock

This commit is contained in:
Christian Rocha 2020-05-11 13:01:42 -04:00
parent 7b887b0a05
commit 2a82e2a75e
No known key found for this signature in database
GPG Key ID: D6CC7A16E5878018
1 changed files with 17 additions and 2 deletions

View File

@ -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)
}
}
}