Second upload

This commit is contained in:
qi_0527 2024-10-02 00:30:22 +08:00
parent 6af20afa72
commit 6669a9bf3c
4 changed files with 61 additions and 8 deletions

View File

@ -19,11 +19,9 @@ builder.Services.AddCors();
builder.Services.AddControllers();
//執行每日存取剩餘車位
builder.Services.AddScoped<ExcelGenerationService>(); // ExcelGenerationService 註冊為 Scoped
builder.Services.AddHostedService<DailyExcelGenerationService>(); // DailyExcelGenerationService 註冊為 HostedService
// 註冊 BackgroundService
builder.Services.AddScoped<ExcelGenerationService>(); // ExcelGenerationService 下載Excel
builder.Services.AddHostedService<DailyExcelGenerationService>(); // 每天設定ExcelGenerationService 存取剩餘車位
builder.Services.AddHostedService<ParkingLogCleanupService>(); //執行定期清除3個月前剩餘車位
builder.Services.AddHostedService<ParkingUpdateService>(); //執行每一分鐘更新剩餘車位
// 連線PostgreSQL資料庫

View File

@ -85,8 +85,8 @@ public class ParkingUpdateService : BackgroundService
}
}
// 每分鐘執行一次
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
// 每 30 秒執行一次
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
}

View File

@ -23,7 +23,7 @@ namespace Parking_space_WebAPI.BackgroundServices
public Task StartAsync(CancellationToken cancellationToken)
{
TimeSpan scheduledTime = new TimeSpan(23, 59, 0); //設定固定每天存取的時間
TimeSpan scheduledTime = new TimeSpan(0, 19, 0); //設定固定每天存取的時間
var now = DateTime.Now;
var nextRunTime = DateTime.Today.Add(scheduledTime);

View File

@ -0,0 +1,55 @@
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);
}
}
}