PeriodicJob.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using Aitex.Core.RT.Log;
  7. namespace Aitex.Core.Util
  8. {
  9. public class PeriodicJob
  10. {
  11. Thread _thread;
  12. int _interval;
  13. DeviceTimer _elapseTimer;
  14. Func<bool> _func;
  15. CancellationTokenSource _cancelFlag = new CancellationTokenSource(); //for quit thread
  16. ManualResetEvent _waitFlag = new ManualResetEvent(true); //for pause purpose
  17. ManualResetEvent _sleepFlag = new ManualResetEvent(false); //for sleep time
  18. object _locker = new object();
  19. public PeriodicJob(int interval, Func<bool> func, string name, bool isStartNow=false, bool isBackground=true)
  20. {
  21. _thread = new Thread(new ParameterizedThreadStart(ThreadFunction));
  22. _thread.Name = name;
  23. _thread.IsBackground = isBackground;
  24. _interval = interval;
  25. _func = func;
  26. _elapseTimer = new DeviceTimer();
  27. if (isStartNow)
  28. Start();
  29. }
  30. public void Start()
  31. {
  32. //lock (_locker)
  33. {
  34. if (_thread == null)
  35. return;
  36. _waitFlag.Set();
  37. if (_thread.IsAlive)
  38. return;
  39. _thread.Start(this);
  40. _elapseTimer.Start(0);
  41. }
  42. }
  43. public void Pause()
  44. {
  45. //lock (_locker)
  46. {
  47. _waitFlag.Reset();
  48. }
  49. }
  50. public void Stop()
  51. {
  52. try
  53. {
  54. //lock (_locker)
  55. {
  56. _sleepFlag.Set(); //do not sleep
  57. _waitFlag.Set(); //do not pause
  58. _cancelFlag.Cancel(); //quit
  59. if (_thread == null)
  60. return;
  61. if (_thread.ThreadState != ThreadState.Suspended)
  62. {
  63. try
  64. {
  65. _thread.Abort();
  66. }
  67. catch (Exception ex)
  68. {
  69. LOG.Error("Thread aborted exception", ex);
  70. }
  71. }
  72. _thread = null;
  73. }
  74. }
  75. catch (Exception ex)
  76. {
  77. LOG.Error("Thread stop exception", ex);
  78. }
  79. }
  80. void ThreadFunction(object param)
  81. {
  82. PeriodicJob t = (PeriodicJob)param;
  83. t.Run();
  84. }
  85. public void ChangeInterval(int msInterval)
  86. {
  87. _interval = msInterval;
  88. }
  89. void Run()
  90. {
  91. while (!_cancelFlag.IsCancellationRequested)
  92. {
  93. _waitFlag.WaitOne();
  94. _elapseTimer.Start(0);
  95. try
  96. {
  97. if (!_func())
  98. break;
  99. }
  100. catch (Exception ex)
  101. {
  102. LOG.Write(ex);
  103. }
  104. _sleepFlag.WaitOne(Math.Max(_interval - (int)_elapseTimer.GetElapseTime(), 30));
  105. }
  106. }
  107. }
  108. }