feat: 优化 timer 包的 GetTicker 获取到的为内置定时器池中的定时器,可通过 timer.NewTimer 创建定时器池另行使用

This commit is contained in:
kercylan98 2023-12-21 14:22:18 +08:00
parent 2ff7db96d2
commit 1ae1c8d65c
2 changed files with 37 additions and 13 deletions

View File

@ -15,3 +15,7 @@ const (
const (
NoMark = "" // 没有设置标记的定时器
)
const (
DefaultTickerPoolSize = 96
)

View File

@ -1,35 +1,55 @@
package timer
import (
"fmt"
"sync"
"github.com/RussellLuo/timingwheel"
)
var tickerPoolSize = 96
var timer = new(Timer)
var (
tickerPoolSize = DefaultTickerPoolSize
standardTimer = NewTimer(tickerPoolSize)
)
// SetTickerPoolSize 设置定时器池大小
// - 默认值为 96,当定时器池中的定时器不足时,会自动创建新的定时器,当定时器释放时,会将多余的定时器进行释放,否则将放入定时器池中
// - 默认值为 DefaultTickerPoolSize,当定时器池中的定时器不足时,会自动创建新的定时器,当定时器释放时,会将多余的定时器进行释放,否则将放入定时器池中
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
_ = standardTimer.ChangeTickerPoolSize(size)
}
func GetTicker(size int, options ...Option) *Ticker {
return timer.NewTicker(size, options...)
return standardTimer.NewTicker(size, options...)
}
func NewTimer(tickerPoolSize int) *Timer {
if tickerPoolSize <= 0 {
panic(fmt.Errorf("timer tickerPoolSize must greater than 0, got: %d", tickerPoolSize))
}
return &Timer{
tickerPoolSize: tickerPoolSize,
}
}
type Timer struct {
tickers []*Ticker
lock sync.Mutex
tickers []*Ticker
lock sync.Mutex
tickerPoolSize int
}
// ChangeTickerPoolSize 改变定时器池大小
// - 当传入的大小小于或等于 0 时,将会返回错误,并且不会发生任何改变
func (slf *Timer) ChangeTickerPoolSize(size int) error {
if size <= 0 {
return fmt.Errorf("timer tickerPoolSize must greater than 0, got: %d", tickerPoolSize)
}
slf.lock.Lock()
defer slf.lock.Unlock()
slf.tickerPoolSize = size
return nil
}
// NewTicker 获取一个新的定时器
func (slf *Timer) NewTicker(size int, options ...Option) *Ticker {
slf.lock.Lock()
defer slf.lock.Unlock()