@@ -17,6 +17,7 @@ package database
1717
1818import (
1919 "errors"
20+ "sync"
2021 "time"
2122
2223 "github.com/dgraph-io/badger/v3"
@@ -31,8 +32,8 @@ type BadgerGarbageCollector struct {
3132 db * badger.DB
3233 log * logr.Logger
3334 // flow control
34- timer * time.Timer
35- stop chan struct {}
35+ timer * time.Timer
36+ running sync. Mutex
3637}
3738
3839// NewBadgerGarbageCollector creates and returns a new
@@ -43,40 +44,33 @@ func NewBadgerGarbageCollector(db *badger.DB, interval time.Duration, log *logr.
4344
4445 db : db ,
4546 log : log ,
46-
47- timer : time .NewTimer (interval ),
48- stop : make (chan struct {}),
4947 }
5048}
5149
52- // Run repeatedly runs the BadgerDB garbage collector with a delay inbetween
50+ // Start repeatedly runs the BadgerDB garbage collector with a delay inbetween
5351// runs.
5452//
55- // This is a blocking operation, so it should be run as a separate goroutine .
53+ // This is a non- blocking operation.
5654// To stop the garbage collector, call Stop().
57- func (gc * BadgerGarbageCollector ) Run () {
55+ func (gc * BadgerGarbageCollector ) Start () {
5856 gc .log .Info ("Starting Badger GC" )
59- for {
60- select {
61- case <- gc .timer .C :
62- gc .discardValueLogFiles ()
63- gc .timer .Reset (gc .Interval )
64- case <- gc .stop :
65- gc .timer .Stop ()
66- gc .log .Info ("Stopped Badger GC" )
67- gc .stop <- struct {}{}
68- return
69- }
70- }
57+ gc .timer = time .AfterFunc (gc .Interval , func () {
58+ gc .running .Lock ()
59+ gc .discardValueLogFiles ()
60+ gc .running .Unlock ()
61+ gc .timer .Reset (gc .Interval )
62+ })
7163}
7264
7365// Stop blocks until the garbage collector has been stopped.
7466//
7567// To avoid GC Errors, call Stop() before closing the database.
7668func (gc * BadgerGarbageCollector ) Stop () {
7769 gc .log .Info ("Sending stop to Badger GC" )
78- gc .stop <- struct {}{}
79- <- gc .stop
70+ gc .timer .Stop ()
71+ gc .running .Lock ()
72+ gc .running .Unlock ()
73+ gc .log .Info ("Stopped Badger GC" )
8074}
8175
8276// upper bound for loop
0 commit comments