2025-09-15 16:51:17 +08:00
|
|
|
|
using Autofac;
|
|
|
|
|
|
using OpenAuth.App.ServiceApp.DroneDocking;
|
2025-09-03 15:03:07 +08:00
|
|
|
|
|
|
|
|
|
|
namespace OpenAuth.WebApi.SystemTask;
|
|
|
|
|
|
|
|
|
|
|
|
public class DelayedExecutionService : BackgroundService
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly ILogger<DelayedExecutionService> _logger;
|
2025-09-15 16:51:17 +08:00
|
|
|
|
private readonly ILifetimeScope _lifetimeScope;
|
2025-09-03 15:03:07 +08:00
|
|
|
|
|
2025-09-15 16:51:17 +08:00
|
|
|
|
public DelayedExecutionService(ILogger<DelayedExecutionService> logger, ILifetimeScope lifetimeScope)
|
2025-09-03 15:03:07 +08:00
|
|
|
|
{
|
|
|
|
|
|
_logger = logger;
|
2025-09-15 16:51:17 +08:00
|
|
|
|
//_droneDockApp = droneDockApp;
|
|
|
|
|
|
_lifetimeScope = lifetimeScope;
|
2025-09-03 15:03:07 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
|
|
|
|
{
|
|
|
|
|
|
_logger.LogInformation("定时任务已启动,将每5秒执行一次");
|
|
|
|
|
|
|
|
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
await PerformDelayedTask();
|
|
|
|
|
|
// 等待5秒
|
2025-09-09 10:32:08 +08:00
|
|
|
|
await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken);
|
2025-09-03 15:03:07 +08:00
|
|
|
|
}
|
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
|
{
|
2025-09-06 09:46:27 +08:00
|
|
|
|
_logger.LogInformation("无人机状态上报任务被取消");
|
2025-09-03 15:03:07 +08:00
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
2025-09-06 09:46:27 +08:00
|
|
|
|
_logger.LogError(ex, "无人机状态上报任务发生错误");
|
2025-09-03 15:03:07 +08:00
|
|
|
|
// 即使出错也继续下一次执行
|
|
|
|
|
|
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
private async Task PerformDelayedTask()
|
|
|
|
|
|
{
|
2025-09-15 16:51:17 +08:00
|
|
|
|
await using (var scope = _lifetimeScope.BeginLifetimeScope())
|
|
|
|
|
|
{
|
|
|
|
|
|
// 2. 从子作用域中解析 AppService 实例(InstancePerLifetimeScope 服务)
|
|
|
|
|
|
var appService = scope.Resolve<DroneDockApp>();
|
|
|
|
|
|
try
|
|
|
|
|
|
{
|
|
|
|
|
|
// 3. 调用 app 服务类的方法
|
|
|
|
|
|
await appService.ReportDroneStatus();
|
|
|
|
|
|
_logger.LogInformation("ReportDroneStatus 方法执行成功");
|
|
|
|
|
|
}
|
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
|
{
|
|
|
|
|
|
_logger.LogError(ex, "ReportDroneStatus 方法执行失败");
|
|
|
|
|
|
}
|
|
|
|
|
|
} // 4. 子作用域释放,AppService 及内部资源(如数据库连接)自动释放
|
|
|
|
|
|
|
2025-09-03 15:03:07 +08:00
|
|
|
|
await Task.CompletedTask;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|