| 1 |
package cache |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"sync" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
type janitor struct { |
| 11 |
ctx context.Context |
| 12 |
interval time.Duration |
| 13 |
done chan struct{} |
| 14 |
once sync.Once |
| 15 |
} |
| 16 |
|
| 17 |
func newJanitor(ctx context.Context, interval time.Duration) *janitor { |
| 18 |
j := &janitor{ |
| 19 |
ctx: ctx, |
| 20 |
interval: interval, |
| 21 |
done: make(chan struct{}), |
| 22 |
} |
| 23 |
return j |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
func (j *janitor) stop() { |
| 28 |
j.once.Do(func() { close(j.done) }) |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
func (j *janitor) run(cleanup func()) { |
| 33 |
go func() { |
| 34 |
ticker := time.NewTicker(j.interval) |
| 35 |
defer ticker.Stop() |
| 36 |
for { |
| 37 |
select { |
| 38 |
case <-ticker.C: |
| 39 |
cleanup() |
| 40 |
case <-j.done: |
| 41 |
cleanup() |
| 42 |
return |
| 43 |
case <-j.ctx.Done(): |
| 44 |
j.stop() |
| 45 |
} |
| 46 |
} |
| 47 |
}() |
| 48 |
} |