parking-webapi/WebApi_data_value/Services/ParkingLogCleanupService.cs

56 lines
1.8 KiB
C#
Raw Permalink Normal View History

2024-10-02 00:30:22 +08:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Parking_space_WebAPI.Services;
public class ParkingLogCleanupService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public ParkingLogCleanupService(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _scopeFactory.CreateScope())
{
var _context = scope.ServiceProvider.GetRequiredService<SqlContext>();
try
{
// 計算三個月前的日期
DateTime threeMonthsAgo = DateTime.Now.AddMonths(-3);
// 查找三個月前的資料
var oldLogs = await _context.ParkingLogs
.Where(log => log.Timestamp < threeMonthsAgo)
.ToListAsync();
if (oldLogs.Any())
{
_context.ParkingLogs.RemoveRange(oldLogs);
await _context.SaveChangesAsync();
Console.WriteLine($"{oldLogs.Count} old parking logs deleted.");
}
}
catch (Exception ex)
{
// 錯誤顯示
Console.WriteLine($"An error occurred during cleanup: {ex.Message}");
}
}
// 每 24 小時執行一次清理
await Task.Delay(TimeSpan.FromDays(1), stoppingToken);
}
}
}