github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/pools/timer.go (about) 1 package pools 2 3 import ( 4 "sync" 5 "time" 6 ) 7 8 /* 9 Creation Time: 2019 - Aug - 02 10 Created by: (ehsan) 11 Maintainers: 12 1. Ehsan N. Moosa (E2) 13 Auditor: Ehsan N. Moosa (E2) 14 */ 15 16 var timerPool sync.Pool 17 18 func AcquireTimer(timeout time.Duration) *time.Timer { 19 tv := timerPool.Get() 20 if tv == nil { 21 return time.NewTimer(timeout) 22 } 23 24 t := tv.(*time.Timer) //nolint:forcetypeassert 25 if t.Reset(timeout) { 26 panic("BUG: Active timer trapped into acquireTimer()") 27 } 28 29 return t 30 } 31 32 func ReleaseTimer(t *time.Timer) { 33 if !t.Stop() { 34 // Collect possibly added time from the channel 35 // if timer has been stopped and nobody collected its value. 36 select { 37 case <-t.C: 38 default: 39 } 40 } 41 timerPool.Put(t) 42 } 43 44 func ResetTimer(t *time.Timer, period time.Duration) { 45 if !t.Stop() { 46 select { 47 case <-t.C: 48 default: 49 } 50 } 51 t.Reset(period) 52 }