CycleService.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Threading;
  3. using VCommon.Logging;
  4. namespace VCommon.Services
  5. {
  6. public abstract class CycleService : IService
  7. {
  8. private Thread _thread;
  9. private bool _isRunning;
  10. protected int SecLoopInterval = 30;
  11. protected int MsWaitStop = 5000;
  12. private void CycleRun()
  13. {
  14. while (_isRunning)
  15. {
  16. try
  17. {
  18. Run();
  19. }
  20. catch (Exception e)
  21. {
  22. Logger.Error("Exception in CycleRun", e);
  23. }
  24. for (var i = 0; i < SecLoopInterval && _isRunning; i++) Thread.Sleep(1000);
  25. }
  26. }
  27. protected abstract void Run();
  28. public void Start()
  29. {
  30. _isRunning = true;
  31. _thread = new Thread(CycleRun) { Name = GetType().Name };
  32. _thread.Start();
  33. }
  34. public void Stop()
  35. {
  36. _isRunning = false;
  37. _thread.Join(MsWaitStop);
  38. _thread.Abort();
  39. }
  40. }
  41. }