| 1 |
package timers |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
var timerPool sync.Pool |
| 9 |
|
| 10 |
// AcquireTimer from pool. |
| 11 |
func AcquireTimer(d time.Duration) *time.Timer { |
| 12 |
v := timerPool.Get() |
| 13 |
if v == nil { |
| 14 |
return time.NewTimer(d) |
| 15 |
} |
| 16 |
|
| 17 |
tm := v.(*time.Timer) |
| 18 |
if tm.Reset(d) { |
| 19 |
panic("Received an active timer from the pool!") |
| 20 |
} |
| 21 |
return tm |
| 22 |
} |
| 23 |
|
| 24 |
// ReleaseTimer to pool. |
| 25 |
func ReleaseTimer(tm *time.Timer) { |
| 26 |
if !tm.Stop() { |
| 27 |
// Do not reuse timer that has been already stopped. |
| 28 |
// See https://groups.google.com/forum/#!topic/golang-nuts/-8O3AknKpwk |
| 29 |
return |
| 30 |
} |
| 31 |
timerPool.Put(tm) |
| 32 |
} |