You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.0 KiB

12 months ago
package timex
import (
"errors"
"git.diulo.com/mogfee/kit/lang"
"time"
)
var errTimeout = errors.New("timeout")
type (
Ticker interface {
Chan() <-chan time.Time
Stop()
}
FakeTicker interface {
Ticker
Done()
Tick()
Wait(d time.Duration) error
}
fakeTicker struct {
c chan time.Time
done chan lang.PlaceholderType
}
realTicker struct {
*time.Ticker
}
)
func NewTicker(d time.Duration) Ticker {
return &realTicker{
Ticker: time.NewTicker(d),
}
}
func (r *realTicker) Chan() <-chan time.Time {
return r.C
}
func NewFakeTicker() FakeTicker {
return &fakeTicker{
c: make(chan time.Time, 1),
done: make(chan lang.PlaceholderType, 1),
}
}
func (f *fakeTicker) Chan() <-chan time.Time {
return f.c
}
func (f *fakeTicker) Stop() {
close(f.c)
}
func (f *fakeTicker) Done() {
f.done <- lang.Placeholder
}
func (f *fakeTicker) Tick() {
f.c <- time.Now()
}
func (f *fakeTicker) Wait(d time.Duration) error {
select {
case <-time.After(d):
return errTimeout
case <-f.done:
return nil
}
}