using System; using System.Diagnostics; using System.Reflection; using System.Timers; using SHJX.Service.Common.Logging; using Microsoft.Extensions.Logging; namespace SHJX.Service.Common.UserTimer { /// /// Timer封装类,定义过程统一 /// public class TimerProcessor { private static readonly ILogger logger = LogFactory.BuildLogger(typeof(TimerProcessor)); private readonly string _timerName; public event Action OnTimer; private readonly Timer _timer; private bool _timerActive; private int _heartBeat; public TimerProcessor(string timerName, double interval) { _timerName = timerName; _timer = new Timer { Interval = interval }; _timer.Elapsed += Timer_Elapsed; } [DebuggerStepThrough] private void Timer_Elapsed(object sender, ElapsedEventArgs e) { if (_timerActive) return; if (++_heartBeat >= int.MaxValue) _heartBeat = 0; var sw = new Stopwatch(); sw.Start(); try { _timerActive = true; OnTimer?.Invoke(); } catch (Exception exception) { logger.LogError("The timer {0} has a exception {1}", _timerName, exception.Message); } finally { sw.Stop(); _timerActive = false; } } public void Start() { if (_timer.Enabled) return; _timer.Enabled = true; logger.LogDebug("The timer {0} started.", this._timerName); } public void Stop() { if (!_timer.Enabled) return; _timer.Enabled = false; logger.LogDebug("The timer {0} stopped.", this._timerName); } public double GetInterval() { return _timer.Interval; } } }