using Mall.Common.Plugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Mall.WebApi.Timers
{
    public class TimerJobj
    {

        static System.Timers.Timer timer1;  //计时器

        public static void RunTimer()
        {
            LogHelper.Write("进来了 。。。 定时器启动");
            timer1 = new System.Timers.Timer();
            timer1.Interval = 1000 * (60 * 60); //60分钟
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(ClearFile);
            timer1.Enabled = true;
        }

        public static void RunStop() {
            LogHelper.Write("定时器停止运行......");
            timer1.Enabled = false;
        }

        /// <summary>
        /// 防止重置
        /// </summary>
        private static int inTimer = 0;

        /// <summary>
        /// 清理文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void ClearFile(object sender, System.Timers.ElapsedEventArgs e) {
            if (Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                if (DateTime.Now.Hour == 1)
                {
                    LogHelper.Write("开始清理临时文件");

                    string rootBook = AppDomain.CurrentDomain.BaseDirectory;
                    try
                    {
                        DirectoryInfo dir = new DirectoryInfo(rootBook + "/upfile/temporary");
                        DirectoryInfo[] dirArr = dir.GetDirectories();
                        foreach (DirectoryInfo item in dirArr)
                        {
                            if (item.CreationTime < DateTime.Now.AddDays(-1))
                                item.Delete(true);
                        }
                        foreach (FileInfo fi in dir.GetFiles())
                        {
                            if (fi.CreationTime < DateTime.Now.AddDays(-1))
                                fi.Delete();
                        }
                    }
                    catch
                    {
                        LogHelper.Write("清理临时文件失败");
                    }
                }
                Interlocked.Exchange(ref inTimer, 0);
            }
        }
    }
}
