PeriodicBackgroundWorkerBase.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using Abp.Threading.Timers;
  3. namespace Abp.Threading.BackgroundWorkers
  4. {
  5. /// <summary>
  6. /// Extends <see cref="BackgroundWorkerBase"/> to add a periodic running Timer.
  7. /// </summary>
  8. public abstract class PeriodicBackgroundWorkerBase : BackgroundWorkerBase
  9. {
  10. protected readonly AbpTimer Timer;
  11. /// <summary>
  12. /// Initializes a new instance of the <see cref="PeriodicBackgroundWorkerBase"/> class.
  13. /// </summary>
  14. /// <param name="timer">A timer.</param>
  15. protected PeriodicBackgroundWorkerBase(AbpTimer timer)
  16. {
  17. Timer = timer;
  18. Timer.Elapsed += Timer_Elapsed;
  19. }
  20. public override void Start()
  21. {
  22. base.Start();
  23. Timer.Start();
  24. }
  25. public override void Stop()
  26. {
  27. Timer.Stop();
  28. base.Stop();
  29. }
  30. public override void WaitToStop()
  31. {
  32. Timer.WaitToStop();
  33. base.WaitToStop();
  34. }
  35. /// <summary>
  36. /// Handles the Elapsed event of the Timer.
  37. /// </summary>
  38. private void Timer_Elapsed(object sender, System.EventArgs e)
  39. {
  40. try
  41. {
  42. DoWork();
  43. }
  44. catch (Exception ex)
  45. {
  46. Logger.Warn(ex.ToString(), ex);
  47. }
  48. }
  49. /// <summary>
  50. /// Periodic works should be done by implementing this method.
  51. /// </summary>
  52. protected abstract void DoWork();
  53. }
  54. }