2020-05-05 13:36:46 -04:00
|
|
|
package tea
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-05-11 12:54:44 -04:00
|
|
|
// NewEveryMsg is used by Every to create a new message. It contains the time
|
2020-05-05 14:26:06 -04:00
|
|
|
// at which the timer finished.
|
|
|
|
type NewEveryMsg func(time.Time) Msg
|
|
|
|
|
2020-05-05 13:36:46 -04:00
|
|
|
// Every is a subscription that ticks with the system clock at the given
|
2020-05-11 13:01:42 -04:00
|
|
|
// duration, similar to cron. It's particularly useful if you have several
|
|
|
|
// subscriptions that need to run in sync.
|
2020-05-05 13:36:46 -04:00
|
|
|
//
|
2020-05-11 13:01:42 -04:00
|
|
|
// TODO: make it cancelable.
|
2020-05-05 14:26:06 -04:00
|
|
|
func Every(duration time.Duration, newMsg NewEveryMsg) Sub {
|
2020-05-05 13:36:46 -04:00
|
|
|
return func() Msg {
|
|
|
|
n := time.Now()
|
|
|
|
d := n.Truncate(duration).Add(duration).Sub(n)
|
|
|
|
t := time.NewTimer(d)
|
|
|
|
select {
|
2020-05-05 14:26:06 -04:00
|
|
|
case now := <-t.C:
|
|
|
|
return newMsg(now)
|
2020-05-05 13:36:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-05-11 13:01:42 -04:00
|
|
|
|
|
|
|
// 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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|