2.0 KiB
2.0 KiB
Cleanup Windows
Schedule retention cleanup during specific time windows.
Overview
Cleanup windows allow you to run retention policy cleanup during off-peak hours (e.g., 2-6 AM UTC) to minimize impact on production workloads.
Configuration
builder.Services.AddPostgresRetentionPolicies(options =>
{
options.Enabled = true;
options.CleanupInterval = TimeSpan.FromHours(1);
options.UseCleanupWindow = true;
options.CleanupWindowStart = TimeSpan.FromHours(2); // 2 AM UTC
options.CleanupWindowEnd = TimeSpan.FromHours(6); // 6 AM UTC
});
Cleanup Window Logic
private bool IsWithinCleanupWindow()
{
if (!_options.UseCleanupWindow)
return true; // Always run if window disabled
var now = DateTime.UtcNow.TimeOfDay;
var start = _options.CleanupWindowStart;
var end = _options.CleanupWindowEnd;
if (start < end)
{
// Normal window (e.g., 2 AM to 6 AM)
return now >= start && now < end;
}
else
{
// Window crosses midnight (e.g., 10 PM to 2 AM)
return now >= start || now < end;
}
}
Examples
Off-Peak Hours (2-6 AM UTC)
options.CleanupWindowStart = TimeSpan.FromHours(2); // 2 AM
options.CleanupWindowEnd = TimeSpan.FromHours(6); // 6 AM
Night Window Crossing Midnight
options.CleanupWindowStart = TimeSpan.FromHours(22); // 10 PM
options.CleanupWindowEnd = TimeSpan.FromHours(4); // 4 AM
Weekend Only
For weekend-only cleanup, implement custom logic:
protected override async Task ExecuteAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
if (DateTime.UtcNow.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)
{
await RunCleanupAsync();
}
await Task.Delay(TimeSpan.FromHours(1), ct);
}
}