go-zero/core/timex/ticker.go

81 lines
1.2 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package timex
import (
"errors"
"time"
"github.com/zeromicro/go-zero/core/lang"
2020-07-26 17:09:05 +08:00
)
2022-02-09 14:40:05 +08:00
// errTimeout indicates a timeout.
var errTimeout = errors.New("timeout")
2020-07-26 17:09:05 +08:00
type (
2021-02-24 16:27:11 +08:00
// Ticker interface wraps the Chan and Stop methods.
2020-07-26 17:09:05 +08:00
Ticker interface {
Chan() <-chan time.Time
Stop()
}
2021-02-24 16:27:11 +08:00
// FakeTicker interface is used for unit testing.
2020-07-26 17:09:05 +08:00
FakeTicker interface {
Ticker
Done()
Tick()
Wait(d time.Duration) error
}
fakeTicker struct {
c chan time.Time
done chan lang.PlaceholderType
}
realTicker struct {
*time.Ticker
}
)
2021-02-24 16:27:11 +08:00
// NewTicker returns a Ticker.
2020-07-26 17:09:05 +08:00
func NewTicker(d time.Duration) Ticker {
return &realTicker{
Ticker: time.NewTicker(d),
}
}
func (rt *realTicker) Chan() <-chan time.Time {
return rt.C
}
2021-02-24 16:27:11 +08:00
// NewFakeTicker returns a FakeTicker.
2020-07-26 17:09:05 +08:00
func NewFakeTicker() FakeTicker {
return &fakeTicker{
c: make(chan time.Time, 1),
done: make(chan lang.PlaceholderType, 1),
}
}
func (ft *fakeTicker) Chan() <-chan time.Time {
return ft.c
}
func (ft *fakeTicker) Done() {
ft.done <- lang.Placeholder
}
func (ft *fakeTicker) Stop() {
close(ft.c)
}
func (ft *fakeTicker) Tick() {
ft.c <- time.Now()
2020-07-26 17:09:05 +08:00
}
func (ft *fakeTicker) Wait(d time.Duration) error {
select {
case <-time.After(d):
2022-02-09 14:40:05 +08:00
return errTimeout
2020-07-26 17:09:05 +08:00
case <-ft.done:
return nil
}
}