-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcleaner.go
66 lines (60 loc) · 1.13 KB
/
cleaner.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
package imcache
import (
"errors"
"sync"
"time"
)
// eremover is an interface that wraps the RemoveExpired method.
type eremover interface {
RemoveExpired()
}
func newCleaner() *cleaner {
return &cleaner{
stopCh: make(chan struct{}),
doneCh: make(chan struct{}),
}
}
type cleaner struct {
stopCh chan struct{}
doneCh chan struct{}
mu sync.Mutex
running bool
}
func (c *cleaner) start(r eremover, interval time.Duration) error {
if interval <= 0 {
return errors.New("imcache: interval must be greater than 0")
}
c.mu.Lock()
defer c.mu.Unlock()
if c.running {
return errors.New("imcache: cleaner already running")
}
c.running = true
c.stopCh = make(chan struct{})
c.doneCh = make(chan struct{})
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
r.RemoveExpired()
case <-c.stopCh:
close(c.doneCh)
return
}
}
}()
return nil
}
func (c *cleaner) stop() {
c.mu.Lock()
defer c.mu.Unlock()
if !c.running {
return
}
c.running = false
close(c.stopCh)
// Wait for the cleaner goroutine to stop while holding the lock.
<-c.doneCh
}