49 lines
786 B
Go
49 lines
786 B
Go
|
package ticker
|
||
|
|
||
|
import (
|
||
|
"github.com/stretchr/testify/assert"
|
||
|
"testing"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func TestTicker(t *testing.T) {
|
||
|
now := time.Now()
|
||
|
// 记录初始时间
|
||
|
data := []int64{
|
||
|
now.Unix(),
|
||
|
}
|
||
|
expected := []int64{
|
||
|
now.Unix(),
|
||
|
}
|
||
|
|
||
|
// 预期每隔一秒收到一个信号
|
||
|
for i := 0; i < 3; i++ {
|
||
|
expected = append(expected, now.Add(time.Duration(i)*time.Second).Unix())
|
||
|
}
|
||
|
|
||
|
done := make(chan struct{})
|
||
|
ticker := NewTicker(time.Second)
|
||
|
ticker.Start()
|
||
|
|
||
|
go func() {
|
||
|
for {
|
||
|
select {
|
||
|
case <-done:
|
||
|
return
|
||
|
case t := <-ticker.C:
|
||
|
data = append(data, t.Unix())
|
||
|
}
|
||
|
}
|
||
|
}()
|
||
|
|
||
|
go func() {
|
||
|
// 设置成3秒有时候会有误差
|
||
|
time.Sleep(2500 * time.Millisecond)
|
||
|
ticker.Stop()
|
||
|
close(done)
|
||
|
}()
|
||
|
|
||
|
time.Sleep(3 * time.Second)
|
||
|
assert.Equal(t, expected, data)
|
||
|
}
|