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-05 14:26:06 -04:00
|
|
|
// duration.
|
2020-05-05 13:36:46 -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
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|