-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
67 lines (58 loc) · 1.42 KB
/
timer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package again
import (
"time"
)
// TimerPool is a pool of timers.
type TimerPool struct {
ch chan *time.Timer // Channel of timers.
duration time.Duration // Duration of the timers.
}
// NewTimerPool creates a new timer pool.
func NewTimerPool(size int, timeout time.Duration) *TimerPool {
// Create the pool.
pool := &TimerPool{
ch: make(chan *time.Timer, size),
duration: timeout,
}
// Create timers and put them into the pool.
for i := 0; i < size; i++ {
t := time.NewTimer(timeout)
t.Stop() // Stop the timer.
t.Reset(timeout) // Reset the timer before adding it to the channel
// Put the timer into the pool.
pool.ch <- t
}
return pool
}
// Get retrieves a timer from the pool.
func (p *TimerPool) Get() *time.Timer {
// Get a timer from the pool.
return <-p.ch
}
// Put returns a timer back into the pool.
func (p *TimerPool) Put(t *time.Timer) {
// Stop the timer.
t.Stop()
t.Reset(p.duration) // Reset the timer before returning it to the channel
select {
case p.ch <- t:
// Timer was successfully put back into the pool.
default:
// Timer pool is full, discard the timer.
}
}
// Close closes the pool.
func (p *TimerPool) Close() {
// Close the channel.
close(p.ch)
}
// Drain drains the pool.
func (p *TimerPool) Drain() {
// Drain the channel.
for range p.ch {
}
}
// Len returns the number of timers in the pool.
func (p *TimerPool) Len() int {
return len(p.ch)
}