using AlibabaCloud.SDK.Vod20170321; using Coravel.Invocable; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using UserCenter.Model.Enum; using VideoAnalysisCore.Common; using VideoAnalysisCore.Model; using VideoAnalysisCore.Model.Dto; using VideoAnalysisCore.Model.Interface; using VideoAnalysisCore.Model.蓝鲸智库; using Yitter.IdGenerator; namespace VideoAnalysisCore.Job { /// /// 下载视频的任务文件清理任务 /// public class TaskFileClearJob : IInvocable { private readonly Repository videotaskDB; private readonly RedisManager redisManager; public TaskFileClearJob(Repository videotaskDB, RedisManager redisManager) { this.videotaskDB = videotaskDB; this.redisManager = redisManager; } public void DeleteTaskAllCaches() { var startTime = -5; var timeSpan = startTime - 999; // 计算 6 天前已完成任务缓存 DateTime twoDaysAgo = DateTime.Now.AddDays(startTime); DateTime endDaysAgo = DateTime.Now.AddDays(timeSpan); // 查询 2 天前任务执行完成的记录 var completedTasks = videotaskDB.AsQueryable() .Where(t => ( //筛选 结束任务 或者 错误任务 t.LastEnum == Model.Enum.RedisChannelEnum.结束任务 || t.ErrorMessage != null ) && t.EndTime < twoDaysAgo && t.EndTime > endDaysAgo) .Select(s => s.Id) .ToList(); // 遍历查询结果,删除缓存文件 foreach (var taskId in completedTasks) { var path = taskId.ToString().LocalPath(); if (!string.IsNullOrEmpty(path) && Directory.Exists(path)) { try { Directory.Delete(path, true); Console.WriteLine($"已删除缓存文件: {taskId}"); } catch (Exception ex) { Console.WriteLine($"删除缓存文件 {taskId} 时出错: {ex.Message}"); } } } } public async void DeleteTaskVideoCaches() { try { var startTime = -1; var timeSpan = startTime - 999; // 计算 2 天前的时间 DateTime twoDaysAgo = DateTime.Now.AddDays(startTime); DateTime endDaysAgo = DateTime.Now.AddDays(timeSpan); // 查询 2 天前任务执行完成的记录 var completedTasks = videotaskDB.AsQueryable() .Where(t => ( //筛选 结束任务 或者 错误任务 t.LastEnum == Model.Enum.RedisChannelEnum.结束任务 || t.ErrorMessage != null ) && t.EndTime < twoDaysAgo && t.EndTime > endDaysAgo) .Select(s => s.Id) .ToList(); // 遍历查询结果,删除缓存文件 foreach (var taskId in completedTasks) await ExpandFunction.DeleteTaskFileAsync(taskId, redisManager); } catch (Exception ex) { Console.WriteLine($"清理缓存时出错: {ex.Message}"); } } public async Task Invoke() { Console.WriteLine($"{DateTime.Now} 执行=>{this.GetType().FullName}"); DeleteTaskVideoCaches(); DeleteTaskAllCaches(); } } }