You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/timex/ticker.go

81 lines
1.2 KiB
Go

4 years ago
package timex
import (
"errors"
"time"
"github.com/zeromicro/go-zero/core/lang"
4 years ago
)
// errTimeout indicates a timeout.
var errTimeout = errors.New("timeout")
4 years ago
type (
// Ticker interface wraps the Chan and Stop methods.
4 years ago
Ticker interface {
Chan() <-chan time.Time
Stop()
}
// FakeTicker interface is used for unit testing.
4 years ago
FakeTicker interface {
Ticker
Done()
Tick()
Wait(d time.Duration) error
}
fakeTicker struct {
c chan time.Time
done chan lang.PlaceholderType
}
realTicker struct {
*time.Ticker
}
)
// NewTicker returns a Ticker.
4 years ago
func NewTicker(d time.Duration) Ticker {
return &realTicker{
Ticker: time.NewTicker(d),
}
}
func (rt *realTicker) Chan() <-chan time.Time {
return rt.C
}
// NewFakeTicker returns a FakeTicker.
4 years ago
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()
}
func (ft *fakeTicker) Wait(d time.Duration) error {
select {
case <-time.After(d):
return errTimeout
4 years ago
case <-ft.done:
return nil
}
}