using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Options;
|
using System;
|
using System.Threading;
|
using System.Threading.Tasks;
|
using WIDESEA_Core.Core;
|
using WIDESEA_ITaskInfoService;
|
|
namespace WIDESEA_WMSServer.BackgroundServices
|
{
|
/// <summary>
|
/// 自动出库任务后台服务
|
/// 定期检查到期库存并创建出库任务
|
/// </summary>
|
public class AutoOutboundTaskBackgroundService : BackgroundService
|
{
|
private readonly ILogger<AutoOutboundTaskBackgroundService> _logger;
|
private readonly ITaskService _taskService;
|
private readonly AutoOutboundTaskOptions _options;
|
|
public AutoOutboundTaskBackgroundService(
|
ILogger<AutoOutboundTaskBackgroundService> logger,
|
ITaskService taskService,
|
IOptions<AutoOutboundTaskOptions> options)
|
{
|
_logger = logger;
|
_taskService = taskService;
|
_options = options.Value;
|
}
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
{
|
_logger.LogInformation("自动出库任务后台服务已启动");
|
|
if (!_options.Enable)
|
{
|
_logger.LogInformation("自动出库任务功能已禁用,服务退出");
|
return;
|
}
|
|
_logger.LogInformation("自动出库任务检查间隔: {Seconds} 秒", _options.CheckIntervalSeconds);
|
|
while (!stoppingToken.IsCancellationRequested)
|
{
|
try
|
{
|
_logger.LogDebug("开始检查到期库存...");
|
var result = await _taskService.CreateAutoOutboundTasksAsync();
|
|
if (result.Status)
|
{
|
_logger.LogInformation("到期库存检查完成: {Message}", result.Message);
|
}
|
else
|
{
|
_logger.LogWarning("到期库存检查失败: {Message}", result.Message);
|
}
|
}
|
catch (Exception ex)
|
{
|
_logger.LogError(ex, "自动出库任务创建过程中发生异常");
|
}
|
|
var delay = TimeSpan.FromSeconds(_options.CheckIntervalSeconds);
|
_logger.LogDebug("等待 {Seconds} 秒后进行下次检查", delay.TotalSeconds);
|
await Task.Delay(delay, stoppingToken);
|
}
|
|
_logger.LogInformation("自动出库任务后台服务已停止");
|
}
|
|
public override async Task StopAsync(CancellationToken cancellationToken)
|
{
|
_logger.LogInformation("正在停止自动出库任务后台服务...");
|
await base.StopAsync(cancellationToken);
|
}
|
}
|
}
|