CacheCleanupService.kt
package nl.johnvanweel.kikker
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import java.io.File
@Service
class CacheCleanupService(
@Value("\${cache.path:/tmp/kikker}") private val cachePath: String,
@Value("\${cache.max-size-gb:1}") maxSizeGb: Long
) {
private val maxSizeBytes = maxSizeGb * 1024 * 1024 * 1024 // GB to Bytes
@Scheduled(cron = "0 0 * * * *")
fun cleanupCache() {
val cacheDir = File(cachePath)
if (!cacheDir.exists() || !cacheDir.isDirectory) {
return
}
val files = cacheDir.listFiles() ?: return
var currentTotalSize = files.sumOf { it.length() }
if (currentTotalSize <= maxSizeBytes) {
return
}
// Sort by last modified date, oldest first
val sortedFiles = files.sortedBy { it.lastModified() }
for (file in sortedFiles) {
val fileSize = file.length()
if (file.delete()) {
currentTotalSize -= fileSize
if (currentTotalSize <= maxSizeBytes) {
break
}
}
}
}
}