1
HuBingJie
7 天以前 5da3a276b7847187a7c155ee069d3cd4c9e58074
´úÂë¹ÜÀí/WCS/WCS/WIDESEAWCS_Server/WIDESEAWCS_Tasks/LogJob.cs
@@ -1,50 +1,37 @@
using HslCommunication;
using HslCommunication.Core;
using HslCommunication.WebSocket;
using Microsoft.AspNetCore.Http;
using Microsoft.VisualBasic.FileIO;
using Newtonsoft.Json;
using Quartz;
using Quartz.Util;
using SixLabors.ImageSharp.PixelFormats;
using Quartz;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using WIDESEA_Common.Log;
using WIDESEAWCS_Communicator;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_QuartzJob;
using WIDESEAWCS_QuartzJob.DeviceBase;
using WIDESEAWCS_QuartzJob.StackerCrane.Enum;
namespace WIDESEAWCS_Tasks
{
    [DisallowConcurrentExecution]
    public class LogJob : IJob
    {
        static object sendData = null;
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                Task.Run(() =>
                {
                    try
                    {
                        while (true)
                        {
                            Run(5);
                        }
                    }
                    catch { }
                });
                        WriteLog.GetLog("LogJob").Write($"日志记录:{DateTime.Now}", "LogJob");
                        // è®¾ç½®ä¿ç•™å¤©æ•°ä¸º30天
                        int saveDays = 30;
                        // æ¸…理Log目录下的所有过期文件夹
                        CleanLogDirectory(saveDays);
                        Thread.Sleep(1000 * 10);
                    }
                    catch (Exception ex)
                    {
                        WriteLog.GetLog("LogJob").Write($"日志清理出错:{ex.Message}", "LogJob");
                    }
                });
            }
            catch (Exception ex)
            {
@@ -53,23 +40,91 @@
            return Task.CompletedTask;
        }
        private static void Run(int saveDays)
        /// <summary>
        /// æ¸…理Log目录下的所有过期日志文件夹
        /// </summary>
        /// <param name="saveDays">保留天数</param>
        private static void CleanLogDirectory(int saveDays)
        {
            sendData = new { code = "1002", Messagest = $"车轮SN号:123123123" };
            CacheData.WebSocket.PublishAllClientPayload(sendData.Serialize());
            // èŽ·å–Log目录路径
            var logBasePath = Path.Combine(Environment.CurrentDirectory, "Log");
            if (!Directory.Exists(logBasePath))
            {
                WriteLog.GetLog("LogJob").Write($"Log目录不存在:{logBasePath}", "LogJob");
                return;
            }
            var nowTime = DateTime.Now;
            var cutoffDate = nowTime.AddDays(-saveDays);
            WriteLog.GetLog("LogJob").Write($"开始清理日志,保留天数:{saveDays},截止日期:{cutoffDate:yyyy-MM-dd}", "LogJob");
            // èŽ·å–Log目录下的所有子目录
            var allSubDirs = Directory.GetDirectories(logBasePath, "*", SearchOption.AllDirectories);
            foreach (var dirPath in allSubDirs)
            {
                try
                {
                    // èŽ·å–æ–‡ä»¶å¤¹å
                    var dirName = Path.GetFileName(dirPath);
                    // å°è¯•解析为日期(支持多种格式)
                    if (TryParseDateFolder(dirName, out DateTime folderDate))
                    {
                        // åˆ¤æ–­æ˜¯å¦è¿‡æœŸ
                        if (folderDate < cutoffDate)
                        {
                            WriteLog.GetLog("LogJob").Write($"删除过期日志文件夹:{dirPath},日期:{folderDate:yyyy-MM-dd}", "LogJob");
                            // é€’归删除文件夹及其内容
                            Directory.Delete(dirPath, true);
                        }
                        else
                        {
                            WriteLog.GetLog("LogJob").Write($"保留日志文件夹:{dirPath},日期:{folderDate:yyyy-MM-dd}", "LogJob");
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteLog.GetLog("LogJob").Write($"处理文件夹 {dirPath} æ—¶å‡ºé”™ï¼š{ex.Message}", "LogJob");
                }
            }
            WriteLog.GetLog("LogJob").Write($"日志清理完成", "LogJob");
        }
        public class CacheData
        /// <summary>
        /// å°è¯•解析日期文件夹名称
        /// </summary>
        /// <param name="folderName">文件夹名称</param>
        /// <param name="date">解析出的日期</param>
        /// <returns>是否成功解析</returns>
        private static bool TryParseDateFolder(string folderName, out DateTime date)
        {
            public static WebSocketServer WebSocket = new WebSocketServer();
            public static void StartServer()
            // æ”¯æŒçš„æ—¥æœŸæ ¼å¼
            string[] dateFormats =
            {
                WebSocket = new WebSocketServer();
                WebSocket.ServerStart(1880);
            }
                "yyyy-MM-dd",   // 2025-12-07
                "yyyyMMdd",     // 20251207
                "yyyy_MM_dd",   // 2025_12_07
                "yyyy.MM.dd",   // 2025.12.07
                "yyyyå¹´MM月dd日" // 2025å¹´12月07日
            };
            // å°è¯•解析日期
            bool success = DateTime.TryParseExact(
                folderName,
                dateFormats,
                System.Globalization.CultureInfo.InvariantCulture,
                System.Globalization.DateTimeStyles.None,
                out date
            );
            return success;
        }
    }
}
}