Created
February 28, 2022 14:45
-
-
Save carterpeel/40321296e70ece9489cfc07f9fa62e8a to your computer and use it in GitHub Desktop.
Ticker Pool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tickpool | |
import ( | |
"sync" | |
"time" | |
) | |
func init() { | |
mu = &sync.Mutex{} | |
pool = &sync.Pool{ | |
New: func() interface{} { | |
return &time.Ticker{} | |
}, | |
} | |
} | |
var ( | |
mu *sync.Mutex | |
pool *sync.Pool | |
) | |
func Get(interval time.Duration) (ticker *time.Ticker) { | |
mu.Lock() | |
defer mu.Unlock() | |
ticker = pool.Get().(*time.Ticker) | |
if ticker.C == nil { | |
ticker = time.NewTicker(interval) | |
} else { | |
ticker.Reset(interval) | |
} | |
return ticker | |
} | |
func Put(ticker *time.Ticker) { | |
mu.Lock() | |
defer mu.Unlock() | |
ticker.Stop() | |
pool.Put(ticker) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment