diff --git a/server/conn.go b/server/conn.go index 1e8d784..c6fa0e3 100644 --- a/server/conn.go +++ b/server/conn.go @@ -277,7 +277,7 @@ func (slf *Conn) Write(packet []byte, callback ...func(err error)) { } func (slf *Conn) init() { - if slf.server.ticker != nil { + if slf.server.ticker != nil && slf.server.connTickerSize > 0 { if slf.server.tickerAutonomy { slf.ticker = timer.GetTicker(slf.server.connTickerSize) } else { @@ -335,6 +335,9 @@ func (slf *Conn) init() { func (slf *Conn) Close(err ...error) { slf.mu.Lock() if slf.closed { + if slf.ticker != nil { + slf.ticker.Release() + } slf.mu.Unlock() return } diff --git a/server/lockstep/lockstep.go b/server/lockstep/lockstep.go index 7218876..10ac55d 100644 --- a/server/lockstep/lockstep.go +++ b/server/lockstep/lockstep.go @@ -123,6 +123,9 @@ func (slf *Lockstep[ClientID, Command]) StartBroadcast() { return } slf.running = true + if slf.ticker == nil { + slf.ticker = timer.GetTicker(10) + } slf.runningLock.Unlock() slf.currentFrame = slf.initFrame @@ -175,7 +178,10 @@ func (slf *Lockstep[ClientID, Command]) StopBroadcast() { slf.running = false slf.runningLock.Unlock() - slf.ticker.StopTimer("lockstep") + if slf.ticker != nil { + slf.ticker.Release() + } + slf.ticker = nil slf.OnLockstepStoppedEvent() diff --git a/utils/timer/ticker.go b/utils/timer/ticker.go index 1892181..470498d 100644 --- a/utils/timer/ticker.go +++ b/utils/timer/ticker.go @@ -38,7 +38,11 @@ func (slf *Ticker) Release() { } slf.lock.Unlock() - slf.timer.tickers = append(slf.timer.tickers, slf) + if len(slf.timer.tickers) < tickerPoolSize { + slf.timer.tickers = append(slf.timer.tickers, slf) + } else { + slf.wheel.Stop() + } } // StopTimer 停止特定名称的调度器 diff --git a/utils/timer/timer.go b/utils/timer/timer.go index 3c9f754..c778b92 100644 --- a/utils/timer/timer.go +++ b/utils/timer/timer.go @@ -6,8 +6,21 @@ import ( "github.com/RussellLuo/timingwheel" ) +var tickerPoolSize = 96 + var timer = new(Timer) +// SetTickerPoolSize 设置定时器池大小 +// - 默认值为 96,当定时器池中的定时器不足时,会自动创建新的定时器,当定时器释放时,会将多余的定时器进行释放,否则将放入定时器池中 +func SetTickerPoolSize(size int) { + if size <= 0 { + panic("ticker pool size must be greater than 0") + } + timer.lock.Lock() + defer timer.lock.Unlock() + tickerPoolSize = size +} + func GetTicker(size int, options ...Option) *Ticker { return timer.NewTicker(size, options...) }