Middle+
Implement a cleanup function for periodic removal of outdated data from buckets. How to organize a background goroutine?
sobes.tech AI
Answer from AI
To implement the cleanup function, which periodically clears outdated data from buckets, you can use a goroutine with a timer that runs in the background and performs cleanup at a specified interval.
Example implementation:
package main
import (
"time"
"fmt"
)
type Bucket struct {
data map[string]time.Time // example: key and time of addition
}
func (b *Bucket) Cleanup(expiration time.Duration) {
now := time.Now()
for key, t := range b.data {
if now.Sub(t) > expiration {
delete(b.data, key)
fmt.Println("Deleted outdated key:", key)
}
}
}
func cleanup(buckets []*Bucket, interval time.Duration, expiration time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
for _, b := range buckets {
b.Cleanup(expiration)
}
}
}
}
func main() {
buckets := []*Bucket{
{data: make(map[string]time.Time)},
{data: make(map[string]time.Time)},
}
// Start a background goroutine for cleanup every 10 seconds
go cleanup(buckets, 10*time.Second, 1*time.Minute)
// Main code
select {} // block main to prevent program from exiting
}
Here:
cleanupis a function that runs in a separate goroutine and calls cleanup at intervals.time.Tickeris used for periodic triggering.- The
Cleanupmethod on each bucket removes outdated data based on the given criteria.
Thus, the background goroutine constantly works and keeps the data up-to-date.