using Edu.Common.Plugin;
using System;
using System.IO;
using System.Threading;

namespace Edu.WebApi.Timers
{
    public class TimerJobj
    {

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

        public static void RunTimer()
        {
            timer1 = new System.Timers.Timer();
            timer1.Interval = 1000 * (60 * 60) * 3; //60分钟
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(ClearFile);
            timer1.Enabled = true;
        }

        public static void RunStop() 
        {
            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)
            {
                string rootBook = AppDomain.CurrentDomain.BaseDirectory;
                try
                {
                    LogHelper.Write("开始清理临时文件");
                    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();
                    }

                    #region 导出文件的

                    DirectoryInfo QRdir = new DirectoryInfo(rootBook + "/upfile/ExportFile");
                    foreach (FileInfo fi in QRdir.GetFiles())
                    {
                        if (fi.CreationTime < DateTime.Now.AddDays(-1))
                            fi.Delete();
                    }

                    #endregion
                }
                catch
                {
                    LogHelper.Write("清理临时文件失败");
                }
                Interlocked.Exchange(ref inTimer, 0);
            }
        }
    }
}
