cleanup Function
The cleanup
function allows you to manually remove stale cache entries that haven't been accessed for a specified period. This is useful for managing memory usage and ensuring your cache doesn't grow indefinitely.
Basic Usage
import { cleanup } from '@commandkit/cache';
// Clean up entries older than 24 hours
await cleanup(24 * 60 * 60 * 1000);
How It Works
When you call cleanup
:
- It scans all cache entries
- Identifies entries that haven't been accessed within the specified time period
- Removes those entries from the cache
- Frees up memory for new cache entries
Example Use Cases
Regular Cleanup
// Set up a daily cleanup task
setInterval(
async () => {
try {
// Clean up entries older than 24 hours
await cleanup(24 * 60 * 60 * 1000);
console.log('Cache cleanup completed');
} catch (error) {
console.error('Cache cleanup failed:', error);
}
},
24 * 60 * 60 * 1000,
); // Run daily
Aggressive Cleanup
async function performAggressiveCleanup() {
// Clean up entries older than 1 hour
await cleanup(60 * 60 * 1000);
}
Conservative Cleanup
async function performConservativeCleanup() {
// Clean up entries older than 7 days
await cleanup(7 * 24 * 60 * 60 * 1000);
}
Best Practices
-
Choose Appropriate Time Period:
- Consider your application's memory constraints
- Balance between memory usage and cache effectiveness
- Monitor cache hit rates
-
Schedule Regular Cleanup:
- Set up automated cleanup tasks
- Choose appropriate intervals
- Handle cleanup errors gracefully
-
Monitor Performance:
- Track memory usage
- Monitor cache hit rates
- Adjust cleanup frequency as needed
Common Patterns
Scheduled Cleanup
// Clean up every hour
setInterval(
async () => {
await cleanup(60 * 60 * 1000);
},
60 * 60 * 1000,
);
// Clean up every day
setInterval(
async () => {
await cleanup(24 * 60 * 60 * 1000);
},
24 * 60 * 60 * 1000,
);
Event-based Cleanup
// Clean up when memory usage is high
process.on('warning', async (warning) => {
if (warning.name === 'HeapSizeWarning') {
await cleanup(60 * 60 * 1000); // Clean up entries older than 1 hour
}
});
Manual Cleanup
async function handleLowMemory() {
// Clean up when memory is low
await cleanup(30 * 60 * 1000); // Clean up entries older than 30 minutes
}