using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SmartScanner { class ImageCleanupService { private readonly string _imageDirectory; private readonly int _retentionDays; private Timer _cleanupTimer; private bool _isRunning; public ImageCleanupService(string imageDirectory, int retentionDays) { _imageDirectory = imageDirectory; _retentionDays = retentionDays; } public void Start() { if (_isRunning) return; // 立即执行一次清理 Task.Run(() => CleanupOldImages()); // 设置每天凌晨2点执行清理 var now = DateTime.Now; var nextRunTime = new DateTime(now.Year, now.Month, now.Day, 2, 0, 0).AddDays(1); var dueTime = nextRunTime - now; _cleanupTimer = new Timer(_ => CleanupOldImages(), null, dueTime, TimeSpan.FromDays(1)); _isRunning = true; } public void Stop() { _cleanupTimer?.Dispose(); _isRunning = false; } private void CleanupOldImages() { try { if (!Directory.Exists(_imageDirectory)) return; var cutoffDate = DateTime.Now.AddDays(-_retentionDays); var searchOption = SearchOption.AllDirectories; foreach (var file in Directory.EnumerateFiles(_imageDirectory, "*.*", searchOption)) { try { var fileInfo = new FileInfo(file); if (fileInfo.LastWriteTime < cutoffDate) { File.Delete(file); // 可选:记录删除日志 LogDeletion(file); } } catch (Exception ex) { // 记录错误但继续处理其他文件 LogError($"删除文件失败: {file}", ex); } } } catch (Exception ex) { LogError("清理旧图像时发生错误", ex); } } private void LogDeletion(string filePath) { // 实现日志记录,可以写入文件或数据库 string logMessage = $"{DateTime.Now}: 已删除过期图像 - {filePath}"; System.Diagnostics.Debug.WriteLine(logMessage); } private void LogError(string message, Exception ex) { // 实现错误日志记录 string errorMessage = $"{DateTime.Now}: {message} - {ex.Message}"; System.Diagnostics.Debug.WriteLine(errorMessage); } } }