From db51edfa1cc44932a357d0d2b7d7dc2a934938f9 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 28 Jun 2023 09:42:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20timer.Ticker=20=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E9=99=84=E5=8A=A0=E6=A0=87=E8=AE=B0=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可通过在获取定时器时的可选项 timer.WithMark(string) 对定时器进行标记,通过 Ticker.GetMark() 函数获取标记 --- utils/timer/constants.go | 4 ++++ utils/timer/options.go | 7 +++++++ utils/timer/ticker.go | 13 ++++++++++--- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/utils/timer/constants.go b/utils/timer/constants.go index 3ef5a3d..be07f83 100644 --- a/utils/timer/constants.go +++ b/utils/timer/constants.go @@ -11,3 +11,7 @@ const ( Once = 1 // 一次 Instantly = 0 // 立刻 ) + +const ( + NoMark = "" // 没有设置标记的定时器 +) diff --git a/utils/timer/options.go b/utils/timer/options.go index 9426869..133b4b7 100644 --- a/utils/timer/options.go +++ b/utils/timer/options.go @@ -8,3 +8,10 @@ func WithCaller(handle func(name string, caller func())) Option { ticker.handle = handle } } + +// WithMark 通过特定的标记创建定时器 +func WithMark(mark string) Option { + return func(ticker *Ticker) { + ticker.mark = mark + } +} diff --git a/utils/timer/ticker.go b/utils/timer/ticker.go index 463dedb..f1bf863 100644 --- a/utils/timer/ticker.go +++ b/utils/timer/ticker.go @@ -8,22 +8,29 @@ import ( "github.com/RussellLuo/timingwheel" ) -// Ticker 管理器 +// Ticker 定时器 type Ticker struct { timer *Timer wheel *timingwheel.TimingWheel timers map[string]*Scheduler lock sync.RWMutex handle func(name string, caller func()) + mark string } -// Release 释放管理器,并将管理器重新放回 Timer 池中 +// Mark 获取定时器的标记 +// - 通常用于鉴别定时器来源 +func (slf *Ticker) Mark() string { + return slf.mark +} + +// Release 释放定时器,并将定时器重新放回 Timer 池中 func (slf *Ticker) Release() { slf.timer.lock.Lock() defer slf.timer.lock.Unlock() slf.lock.Lock() - + slf.mark = "" for name, scheduler := range slf.timers { scheduler.close() delete(slf.timers, name)