dotnet-cqrs/docs/event-streaming/retention-policies/cleanup-windows.md

87 lines
2.0 KiB
Markdown

# 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
```csharp
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
```csharp
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)
```csharp
options.CleanupWindowStart = TimeSpan.FromHours(2); // 2 AM
options.CleanupWindowEnd = TimeSpan.FromHours(6); // 6 AM
```
### Night Window Crossing Midnight
```csharp
options.CleanupWindowStart = TimeSpan.FromHours(22); // 10 PM
options.CleanupWindowEnd = TimeSpan.FromHours(4); // 4 AM
```
### Weekend Only
For weekend-only cleanup, implement custom logic:
```csharp
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);
}
}
```
## See Also
- [Retention Policies Overview](README.md)
- [Time-Based Retention](time-based-retention.md)
- [Size-Based Retention](size-based-retention.md)