Learn.VideoAnalysis/VideoAnalysisCore/Job/ClearAllCacheJob.cs

58 lines
1.9 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Coravel.Invocable;
using System;
using System.IO;
using System.Threading.Tasks;
using VideoAnalysisCore.Common;
namespace VideoAnalysisCore.Job
{
/// <summary>
/// 每小时强制清理缓存文件夹下所有内容的任务
/// </summary>
public class ClearAllCacheJob : IInvocable
{
public Task Invoke()
{
try
{
var cacheDir = AppCommon.TaskCachedFile;
if (!Directory.Exists(cacheDir))
{
return Task.CompletedTask;
}
Console.WriteLine($"{DateTime.Now} 开始强制清理缓存目录: {cacheDir}");
// 获取所有子目录
var directories = Directory.GetDirectories(cacheDir);
var i = 0;
foreach (var dir in directories)
{
try
{
// 检查文件夹创建时间如果是30分钟前的则删除防止删除正在运行的任务
if (Directory.GetCreationTime(dir) < DateTime.Now.AddMinutes(-30))
{
Directory.Delete(dir, true);
i++;
}
}
catch (Exception ex)
{
// 正在使用的文件夹会抛出异常,忽略即可
Console.WriteLine($"清理目录 {dir} 时发生错误 (可能正在使用): {ex.Message}");
}
}
Console.WriteLine($"已删除过期缓存数量 {i}");
}
catch (Exception ex)
{
Console.WriteLine($"强制清理缓存任务发生异常: {ex.Message}");
}
return Task.CompletedTask;
}
}
}