Skip to content

Instantly share code, notes, and snippets.

@carterpeel
Created February 28, 2022 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carterpeel/40321296e70ece9489cfc07f9fa62e8a to your computer and use it in GitHub Desktop.
Save carterpeel/40321296e70ece9489cfc07f9fa62e8a to your computer and use it in GitHub Desktop.
Ticker Pool
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