using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Parking_space_WebAPI.Services; // 讓ExcelGenerationService執行每日固定存取 namespace Parking_space_WebAPI.BackgroundServices { public class DailyExcelGenerationService : IHostedService, IDisposable { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; private Timer _timer; public DailyExcelGenerationService(ILogger logger, IServiceProvider serviceProvider) { _logger = logger; _serviceProvider = serviceProvider; } public Task StartAsync(CancellationToken cancellationToken) { TimeSpan scheduledTime = new TimeSpan(23, 59, 0); //設定固定每天存取的時間 var now = DateTime.Now; var nextRunTime = DateTime.Today.Add(scheduledTime); if (now > nextRunTime) { nextRunTime = nextRunTime.AddDays(1); } var timeToGo = nextRunTime - now; _timer = new Timer(GenerateExcel, null, timeToGo, TimeSpan.FromDays(1)); return Task.CompletedTask; } private async void GenerateExcel(object state) { try { using (var scope = _serviceProvider.CreateScope()) { var excelGenerationService = scope.ServiceProvider.GetRequiredService(); await excelGenerationService.GenerateDailyExcel(); } _logger.LogInformation("每日 Excel 檔案已生成。"); } catch (Exception ex) { _logger.LogError(ex, "生成 Excel 檔案時出錯。"); } } public Task StopAsync(CancellationToken cancellationToken) { _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } }