feat: timer.Pool 新增 Release 函数,可主动释放池中的所有定时器及池子本身

This commit is contained in:
kercylan98 2023-12-21 14:43:55 +08:00
parent 50181c7ecb
commit ae98963ecc
2 changed files with 16 additions and 1 deletions

View File

@ -22,6 +22,7 @@ type Pool struct {
tickers []*Ticker
lock sync.Mutex
tickerPoolSize int
closed bool
}
// ChangePoolSize 改变定时器池大小
@ -59,3 +60,17 @@ func (slf *Pool) GetTicker(size int, options ...Option) *Ticker {
ticker.wheel.Start()
return ticker
}
// Release 释放定时器池的资源,释放后由其产生的 Ticker 在 Ticker.Release 后将不再回到池中,而是直接释放
// - 虽然定时器池已被释放,但是依旧可以产出 Ticker
func (slf *Pool) Release() {
slf.lock.Lock()
defer slf.lock.Unlock()
slf.closed = true
for _, ticker := range slf.tickers {
ticker.wheel.Stop()
}
slf.tickers = nil
slf.tickerPoolSize = 0
return
}

View File

@ -39,7 +39,7 @@ func (slf *Ticker) Release() {
}
slf.lock.Unlock()
if len(slf.timer.tickers) < tickerPoolSize {
if len(slf.timer.tickers) < tickerPoolSize && !slf.timer.closed {
slf.timer.tickers = append(slf.timer.tickers, slf)
} else {
slf.wheel.Stop()