-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
janitor.go
48 lines (43 loc) · 830 Bytes
/
janitor.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
package cache
import (
"context"
"sync"
"time"
)
// janitor for collecting expired items and cleaning them.
type janitor struct {
ctx context.Context
interval time.Duration
done chan struct{}
once sync.Once
}
func newJanitor(ctx context.Context, interval time.Duration) *janitor {
j := &janitor{
ctx: ctx,
interval: interval,
done: make(chan struct{}),
}
return j
}
// stop to stop the janitor.
func (j *janitor) stop() {
j.once.Do(func() { close(j.done) })
}
// run with the given cleanup callback function.
func (j *janitor) run(cleanup func()) {
go func() {
ticker := time.NewTicker(j.interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
cleanup()
case <-j.done:
cleanup() // last call
return
case <-j.ctx.Done():
j.stop()
}
}
}()
}