﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TestConsole.Test
{
    public class TimerTest
    {
        private static Timer m_Timer = null;
        private static object m_LockerForTimer = new object();
        private static bool m_IsRunning = false;
        private static DateTime m_LastCallbackTime = new DateTime();

        static TimerTest()
        {
            if (m_Timer == null)
            {
                m_Timer = new Timer(new TimerCallback(OnTimerCallback), null, 0, 10);
            }
        }

        private static void OnTimerCallback(object obj)
        {
            if (m_IsRunning)
            {
                Console.WriteLine("release");
                return;
            }

            lock (m_LockerForTimer)
            {
                try
                {
                    m_IsRunning = true;
                    m_LastCallbackTime = DateTime.Now;

                    //Timer触发事件
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    m_IsRunning = false;
                }
            }
        }


        public static DateTime GetLastCallbackTime()
        {
            return m_LastCallbackTime;
        }


        public static void Dispose()
        {
            m_Timer.Dispose();
        }


        public static bool CheckHealth()
        {
            bool result = false;

            TimeSpan dur = DateTime.Now.Subtract(m_LastCallbackTime).Duration();
            if (dur.TotalMilliseconds <= 120000)
            {
                result = true;
            }

            return result;
        }

    }
}
