parking-webapi/WebApi_data_value/Services/IHostedService.cs

71 lines
2.2 KiB
C#
Raw Permalink Normal View History

2024-10-01 02:30:08 +08:00
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<DailyExcelGenerationService> _logger;
private readonly IServiceProvider _serviceProvider;
private Timer _timer;
public DailyExcelGenerationService(ILogger<DailyExcelGenerationService> logger, IServiceProvider serviceProvider)
{
_logger = logger;
_serviceProvider = serviceProvider;
}
public Task StartAsync(CancellationToken cancellationToken)
{
2024-10-27 21:24:51 +08:00
TimeSpan scheduledTime = new TimeSpan(23, 59, 0); //設定固定每天存取的時間
2024-10-01 02:30:08 +08:00
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<ExcelGenerationService>();
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();
}
}
}