PeriodicJob.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. namespace Aitex.DataAnalysis.Core
  7. {
  8. public class PeriodicJob
  9. {
  10. Thread _thread;
  11. int _interval;
  12. int _tick = 0;
  13. Func<bool> _func;
  14. CancellationTokenSource _cancelFlag = new CancellationTokenSource(); //for quit thread
  15. ManualResetEvent _waitFlag = new ManualResetEvent(true); //for pause purpose
  16. ManualResetEvent _sleepFlag = new ManualResetEvent(false); //for sleep time
  17. public PeriodicJob(int interval, Func<bool> func, string name, bool isStartNow=false, bool isBackground=true)
  18. {
  19. _thread = new Thread(new ParameterizedThreadStart(ThreadFunction));
  20. _thread.Name = name;
  21. _thread.IsBackground = true;
  22. _interval = interval;
  23. _func = func;
  24. if (isStartNow)
  25. Start();
  26. }
  27. public void Start()
  28. {
  29. if (_thread == null)
  30. return;
  31. _waitFlag.Set();
  32. if (_thread.IsAlive)
  33. return;
  34. _thread.Start(this);
  35. }
  36. public void Pause()
  37. {
  38. _waitFlag.Reset();
  39. }
  40. public void Stop()
  41. {
  42. _sleepFlag.Set(); //do not sleep
  43. _waitFlag.Set(); //do not pause
  44. _cancelFlag.Cancel(); //quit
  45. _thread.Abort();
  46. _thread.Join();
  47. _thread = null;
  48. }
  49. void ThreadFunction(object param)
  50. {
  51. PeriodicJob t = (PeriodicJob)param;
  52. t.Run();
  53. }
  54. void Run()
  55. {
  56. while (!_cancelFlag.IsCancellationRequested)
  57. {
  58. _tick = Environment.TickCount;
  59. _waitFlag.WaitOne();
  60. if (!_func())
  61. break;
  62. _sleepFlag.WaitOne(Math.Max(_interval - (Environment.TickCount - _tick), 30));
  63. }
  64. }
  65. }
  66. }