From 45024f3b9fe41131dab65ba0ead4361ad0a0d23b Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 19 Apr 2024 15:10:00 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20timer.Ticker=20?= =?UTF-8?q?=E6=AD=BB=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/timer/ticker.go | 5 +++-- utils/timer/ticker_loop_test.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 utils/timer/ticker_loop_test.go diff --git a/utils/timer/ticker.go b/utils/timer/ticker.go index c739a12..6c4b472 100644 --- a/utils/timer/ticker.go +++ b/utils/timer/ticker.go @@ -151,8 +151,9 @@ func (slf *Ticker) loop(name string, after, interval time.Duration, expr *cronex if slf.handler != nil { scheduler.timer = slf.wheel.ScheduleFunc(scheduler, func() { slf.lock.RLock() - defer slf.lock.RUnlock() - if slf.handler != nil { + handler := slf.handler + slf.lock.RUnlock() + if handler != nil { slf.handler(scheduler.Name(), scheduler.Caller) } }) diff --git a/utils/timer/ticker_loop_test.go b/utils/timer/ticker_loop_test.go new file mode 100644 index 0000000..4b26b4a --- /dev/null +++ b/utils/timer/ticker_loop_test.go @@ -0,0 +1,37 @@ +package timer + +import ( + "github.com/gin-contrib/pprof" + "github.com/gin-gonic/gin" + "github.com/kercylan98/minotaur/utils/times" + "testing" + "time" +) + +func TestTicker_Loop(t *testing.T) { + r := gin.Default() + pprof.Register(r) + + go func() { + r.Run(":9999") + }() + + ticker := GetTicker(10, WithCaller(func(name string, caller func()) { + caller() + })) + + ticker.After("stop", time.Second, func() { + ticker.StopTimer("stop") + t.Log("success") + ticker.After("stop1", time.Second, func() { + ticker.StopTimer("stop1") + t.Log("success1") + ticker.After("stop2", time.Second, func() { + ticker.StopTimer("stop2") + t.Log("success2") + }) + }) + }) + + time.Sleep(times.Week) +}