Files
Docker/CloudBuilder.Topshelf/Task/RunTask.cs
T
2026-09-21 21:31:16 +08:00

97 lines
3.4 KiB
C#

using CliWrap;
using CloudBuilder.Core.DatabaseAccessor.Entity;
using CloudBuilder.Core.DependencyInjection.Task;
using CloudBuilder.Core.Service;
using CloudBuilder.Master.Entity;
using CloudBuilder.Security.Entity;
using CloudBuilder.Security.Service;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CloudBuilder.Topshelf.Task
{
//task:RunTask param_name:param_value
public class RunTask : IScheduleTask
{
private readonly IApplicationService service;
private FileLog log;
public RunTask(IApplicationService service)
{
this.service = service;
log = new FileLog(service.Configuration);
}
public void Run(Dictionary<string, string> bodyDict)
{
log.WriteToFile("RunTask");
try
{
IRepository<SecurityScheduleTaskQueueEntity> taskRepository = service.GetRepository<IRepository<SecurityScheduleTaskQueueEntity>>();
SecurityScheduleTaskQueueEntity[] tasks = taskRepository.DetachedEntities.OrderBy(x => x.QueueId).ToArray();
if (tasks == null || tasks.Length == 0) return;
foreach (var task in tasks)
{
IRepository<DmsFileEntity> repositoryDmsFile = service.GetRepository<IRepository<DmsFileEntity>>();
DmsFileEntity dmsFile = repositoryDmsFile.DetachedEntities.Where(x => x.OrderKey == task.DocumentId).FirstOrDefault();
if (dmsFile == null) return;
RunMyProcess(task.TaskId, task.TaskParam);
dmsFile.TranscodeIndc = YesNoPolicy.YES;
repositoryDmsFile.UpdateNow(dmsFile);
taskRepository.DeleteNow(task);
}
}
catch (Exception ex)
{
log.WriteToFile(ex.Message);
}
}
/// <summary>
/// 执行cmd指令(异步不等待,await要求等待返回,转码太耗时)
/// </summary>
/// <param name="parameters"></param>
public void RunMyProcess(string exePath, string parameters)
{
try
{
//Dockerfile中定义的volumes的映射地址
var rf = service.Configuration["FileServiceSettings:RelativeFileDirectory"];
var af = service.Configuration["FileServiceSettings:AbsoluteFileDirectory"];
parameters = parameters.Replace(rf, af);
log.WriteToFile(exePath + parameters);
if (string.IsNullOrEmpty(exePath)) return;
// 获取异步任务
var commandTask = Cli.Wrap(exePath)
.WithArguments(parameters)
.WithValidation(CommandResultValidation.None) // 关键:允许非0退出码而不抛异常,以便我们能拿到错误输出
.ExecuteAsync();
// 阻塞当前线程,等待任务完成(因为你的外层是同步的 void 方法)
var result = commandTask.Task.GetAwaiter().GetResult();
// 记录退出码和标准错误输出
log.WriteToFile($"FFmpeg ExitCode: {result.ExitCode}");
}
catch (Exception ex)
{
log.WriteToFile(ex.Message);
throw new ValidatedException(ex.Message);
}
}
}
}