github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/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 Copyright Ronak Software Group 2020 15 */ 16 17 var timerPool sync.Pool 18 19 func AcquireTimer(timeout time.Duration) *time.Timer { 20 tv := timerPool.Get() 21 if tv == nil { 22 return time.NewTimer(timeout) 23 } 24 25 t := tv.(*time.Timer) 26 if t.Reset(timeout) { 27 panic("BUG: Active timer trapped into acquireTimer()") 28 } 29 30 return t 31 } 32 33 func ReleaseTimer(t *time.Timer) { 34 if !t.Stop() { 35 // Collect possibly added time from the channel 36 // if timer has been stopped and nobody collected its' value. 37 select { 38 case <-t.C: 39 default: 40 } 41 } 42 timerPool.Put(t) 43 } 44 45 func ResetTimer(t *time.Timer, period time.Duration) { 46 if !t.Stop() { 47 select { 48 case <-t.C: 49 default: 50 } 51 } 52 t.Reset(period) 53 }