You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
2.8 KiB

  1. using Apewer;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;
  6. namespace Apewer.Web
  7. {
  8. internal sealed class CronInstance
  9. {
  10. private Thread _thread = null;
  11. private Action _action = null;
  12. private Type _type = null;
  13. private bool _break = false;
  14. private bool _latest = false;
  15. private CronAttribute _attribute = null;
  16. private Nullable<DateTime> _ended = null;
  17. public CronInvoker Invoker { get; set; }
  18. public Thread Thread
  19. {
  20. get { return _thread; }
  21. }
  22. public bool Alive
  23. {
  24. get { return GetAlive(); }
  25. }
  26. /// <summary>再次启动 Cron 的时间间隔。</summary>
  27. public int Interval
  28. {
  29. get { return GetInterval(); }
  30. }
  31. /// <summary>最后一次检查的 Alive 值。</summary>
  32. public bool Latest
  33. {
  34. get { return _latest; }
  35. set { _latest = value; }
  36. }
  37. public Type Type
  38. {
  39. get { return _type; }
  40. set { _type = value; }
  41. }
  42. public bool Break
  43. {
  44. get { return _break; }
  45. set { _break = value; }
  46. }
  47. public CronAttribute Attribute
  48. {
  49. get { return _attribute; }
  50. set { _attribute = value; }
  51. }
  52. public Nullable<DateTime> Ended
  53. {
  54. get { return _ended; }
  55. set { _ended = value; }
  56. }
  57. public CronInstance()
  58. {
  59. _thread = new Thread(Listen);
  60. _thread.IsBackground = true;
  61. }
  62. void Log(params object[] content) => Invoker?.Log(content);
  63. public void Start()
  64. {
  65. if (Alive) return;
  66. _thread = new Thread(Listen);
  67. _thread.IsBackground = true;
  68. _thread.Start();
  69. }
  70. public void Abort()
  71. {
  72. if (_thread != null)
  73. {
  74. _thread.Abort();
  75. _thread = null;
  76. }
  77. }
  78. int GetInterval()
  79. {
  80. if (Attribute != null) return Attribute.Interval;
  81. return CronAttribute.DefaultInterval;
  82. }
  83. bool GetAlive()
  84. {
  85. if (_thread == null) return false;
  86. if (_thread.IsAlive != true) return false;
  87. if (Thread.ThreadState != ThreadState.Running) return false;
  88. return true;
  89. }
  90. void Listen()
  91. {
  92. if (Type == null) return;
  93. try
  94. {
  95. Activator.CreateInstance(Type);
  96. }
  97. catch (Exception exception)
  98. {
  99. Log(Type.FullName, exception.GetType().FullName, exception.Message);
  100. }
  101. _thread = null;
  102. }
  103. }
  104. }