Files
WCS/Plugins/Wcs/Plugin.Cowain.Wcs/Services/WcsStartUpHostedService.cs
2026-03-02 09:13:29 +08:00

88 lines
3.0 KiB
C#

using Cowain.Base.Helpers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Plugin.Cowain.Wcs.IServices;
using Plugin.Cowain.Wcs.ViewModels;
namespace Plugin.Cowain.Wcs.Services;
public class WcsStartUpHostedService : IHostedService
{
private IServiceScopeFactory _scopeFactory;
private readonly ILogger<WcsStartUpHostedService> _logger;
public WcsStartUpHostedService(IServiceScopeFactory scopeFactory, ILogger<WcsStartUpHostedService> logger)
{
_scopeFactory = scopeFactory;
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("WcsStartUpHostedService Start");
try
{
await FindTaskAsync();
using var scope = _scopeFactory.CreateScope();
var taskHandlers = scope.ServiceProvider.GetRequiredService<IEnumerable<IHostedService>>();
var stationQueueHostedService = taskHandlers.OfType<StationQueueHostedService>().FirstOrDefault();
if (stationQueueHostedService == null)
{
return;
}
stationQueueHostedService.FindTaskAction = async (StationViewModel item) =>
{
await FindTaskAsync();
};
}
catch (Exception ex)
{
_logger.LogError(ex, "WcsStartUpHostedService Start Error");
return;
}
_logger.LogInformation("WcsStartUpHostedService Started");
}
private async Task FindTaskAsync()
{
try
{
using var scope = _scopeFactory.CreateScope();
var wcsParamService = scope.ServiceProvider.GetRequiredService<IWcsParamService>();
// 使用WcsParamService的缓存功能获取参数
var findTaskEnableResult = await wcsParamService.GetParamAsync("FindTaskEnable");
if (findTaskEnableResult.IsSuccess)
{
if (bool.TryParse(findTaskEnableResult.Data!.Param, out bool findTaskEnable) && findTaskEnable)
{
var findFlowTaskService = scope.ServiceProvider.GetRequiredService<IFindFlowTask6180Service>();
await findFlowTaskService.FindTaskAsync();
}
else
{
_logger.LogInformation("任务查找功能已禁用");
}
}
else
{
_logger.LogInformation($"获取FindTaskEnable参数失败: {findTaskEnableResult.ErrorMessage}");
}
}
catch (Exception ex)
{
_logger.LogError(ex, "FindTaskAsync 执行失败");
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("StationQueueHostedService Stop");
_logger.LogInformation("StationQueueHostedService Stoped");
return Task.CompletedTask;
}
}