优化代码

This commit is contained in:
GoEdgeLab
2021-12-08 22:19:15 +08:00
parent c96406ff64
commit 6be26c0ffb
4 changed files with 34 additions and 24 deletions

View File

@@ -63,7 +63,7 @@ func (this *CountryManager) Start() {
events.On(events.EventQuit, func() { events.On(events.EventQuit, func() {
ticker.Stop() ticker.Stop()
}) })
for range ticker.C { for ticker.Next() {
err := this.loop() err := this.loop()
if err != nil { if err != nil {
remotelogs.ErrorObject("COUNTRY_MANAGER", err) remotelogs.ErrorObject("COUNTRY_MANAGER", err)

View File

@@ -67,7 +67,7 @@ func (this *ProvinceManager) Start() {
events.On(events.EventQuit, func() { events.On(events.EventQuit, func() {
ticker.Stop() ticker.Stop()
}) })
for range ticker.C { for ticker.Next() {
err := this.loop() err := this.loop()
if err != nil { if err != nil {
remotelogs.ErrorObject("PROVINCE_MANAGER", err) remotelogs.ErrorObject("PROVINCE_MANAGER", err)

View File

@@ -1,47 +1,43 @@
package utils package utils
import ( import (
"sync"
"time" "time"
) )
// 类似于time.Ticker但能够真正地停止 // Ticker 类似于time.Ticker但能够真正地停止
type Ticker struct { type Ticker struct {
raw *time.Ticker raw *time.Ticker
done chan bool
once sync.Once
S chan bool
C <-chan time.Time C <-chan time.Time
isStopped bool
} }
// 创建新Ticker // NewTicker 创建新Ticker
func NewTicker(duration time.Duration) *Ticker { func NewTicker(duration time.Duration) *Ticker {
raw := time.NewTicker(duration) raw := time.NewTicker(duration)
return &Ticker{ return &Ticker{
raw: raw, raw: raw,
C: raw.C, C: raw.C,
S: make(chan bool, 1), done: make(chan bool, 1),
} }
} }
// 查找下一个Tick // Next 查找下一个Tick
func (this *Ticker) Next() bool { func (this *Ticker) Next() bool {
select { select {
case <-this.raw.C: case <-this.raw.C:
return true return true
case <-this.S: case <-this.done:
return false return false
} }
} }
// 停止 // Stop 停止
func (this *Ticker) Stop() { func (this *Ticker) Stop() {
if this.isStopped { this.once.Do(func() {
return this.raw.Stop()
} this.done <- true
})
this.isStopped = true
this.raw.Stop()
this.S <- true
} }

View File

@@ -41,9 +41,9 @@ func TestTicker2(t *testing.T) {
for { for {
t.Log("loop") t.Log("loop")
select { select {
case <-ticker.C: case <-ticker.raw.C:
t.Log("tick") t.Log("tick")
case <-ticker.S: case <-ticker.done:
return return
} }
} }
@@ -63,3 +63,17 @@ func TestTickerEvery(t *testing.T) {
}) })
wg.Wait() wg.Wait()
} }
func TestTicker_StopTwice(t *testing.T) {
ticker := NewTicker(3 * time.Second)
go func() {
time.Sleep(10 * time.Second)
ticker.Stop()
ticker.Stop()
}()
for ticker.Next() {
t.Log("tick")
}
t.Log("finished")
}