Files
EmailBill/Service/PeriodicBillBackgroundService.cs
孙诚 8dfe7f1688
Some checks failed
Docker Build & Deploy / Build Docker Image (push) Failing after 14s
Docker Build & Deploy / Deploy to Production (push) Has been skipped
结构调整
2026-01-01 12:32:08 +08:00

62 lines
2.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Microsoft.Extensions.Hosting;
namespace Service;
/// <summary>
/// 周期性账单后台服务
/// </summary>
public class PeriodicBillBackgroundService(
IServiceProvider serviceProvider,
ILogger<PeriodicBillBackgroundService> logger
) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("周期性账单后台服务已启动");
while (!stoppingToken.IsCancellationRequested)
{
try
{
var now = DateTime.Now;
// 计算下次执行时间每天早上6点
var nextRun = now.Date.AddHours(6);
if (now >= nextRun)
{
nextRun = nextRun.AddDays(1);
}
var delay = nextRun - now;
logger.LogInformation("下次执行周期性账单检查时间: {NextRun}, 延迟: {Delay}",
nextRun.ToString("yyyy-MM-dd HH:mm:ss"), delay);
await Task.Delay(delay, stoppingToken);
if (stoppingToken.IsCancellationRequested)
break;
// 执行周期性账单检查
using (var scope = serviceProvider.CreateScope())
{
var periodicService = scope.ServiceProvider.GetRequiredService<ITransactionPeriodicService>();
await periodicService.ExecutePeriodicBillsAsync();
}
}
catch (OperationCanceledException)
{
logger.LogInformation("周期性账单后台服务已取消");
break;
}
catch (Exception ex)
{
logger.LogError(ex, "周期性账单后台服务执行出错");
// 出错后等待1小时再重试
await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}
logger.LogInformation("周期性账单后台服务已停止");
}
}