File: janitor.go

package info (click to toggle)
golang-github-code-hex-go-generics-cache 1.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 216 kB
  • sloc: makefile: 2
file content (48 lines) | stat: -rw-r--r-- 830 bytes parent folder | download
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()
			}
		}
	}()
}