TimerProcessor.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using System.Timers;
  5. using SHJX.Service.Common.Logging;
  6. using Microsoft.Extensions.Logging;
  7. namespace SHJX.Service.Common.UserTimer
  8. {
  9. /// <summary>
  10. /// Timer封装类,定义过程统一
  11. /// </summary>
  12. public class TimerProcessor
  13. {
  14. private static readonly ILogger logger = LogFactory.BuildLogger(typeof(TimerProcessor));
  15. private readonly string _timerName;
  16. public event Action OnTimer;
  17. private readonly Timer _timer;
  18. private bool _timerActive;
  19. private int _heartBeat;
  20. public TimerProcessor(string timerName, double interval)
  21. {
  22. _timerName = timerName;
  23. _timer = new Timer
  24. {
  25. Interval = interval
  26. };
  27. _timer.Elapsed += Timer_Elapsed;
  28. }
  29. [DebuggerStepThrough]
  30. private void Timer_Elapsed(object sender, ElapsedEventArgs e)
  31. {
  32. if (_timerActive)
  33. return;
  34. if (++_heartBeat >= int.MaxValue)
  35. _heartBeat = 0;
  36. var sw = new Stopwatch();
  37. sw.Start();
  38. try
  39. {
  40. _timerActive = true;
  41. OnTimer?.Invoke();
  42. }
  43. catch (Exception exception)
  44. {
  45. logger.LogError("The timer {0} has a exception {1}", _timerName, exception.Message);
  46. }
  47. finally
  48. {
  49. sw.Stop();
  50. _timerActive = false;
  51. }
  52. }
  53. public void Start()
  54. {
  55. if (_timer.Enabled) return;
  56. _timer.Enabled = true;
  57. logger.LogDebug("The timer {0} started.", this._timerName);
  58. }
  59. public void Stop()
  60. {
  61. if (!_timer.Enabled) return;
  62. _timer.Enabled = false;
  63. logger.LogDebug("The timer {0} stopped.", this._timerName);
  64. }
  65. public double GetInterval()
  66. {
  67. return _timer.Interval;
  68. }
  69. }
  70. }