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.

95 lines
2.4 KiB

4 years ago
  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. internal bool _latest = false;
  11. internal Type _type = null;
  12. internal Logger _logger = null;
  13. internal Class<DateTime> _ended = null;
  14. internal CronAttribute _attribute = null;
  15. internal CronInvoker _invoker = null;
  16. private Thread _thread = null;
  17. private bool _break = false;
  18. #region properties
  19. // 当前线程正在运行。
  20. public bool Alive { get => GetAlive(); }
  21. // 再次启动 Cron 的时间间隔。
  22. public int Interval { get => GetInterval(); }
  23. // 最后一次检查的 Alive 值。
  24. public bool Latest { get => _latest; }
  25. // Cron 类型。
  26. public Type Type { get => _type; }
  27. public CronAttribute Attribute { get => _attribute; }
  28. public Class<DateTime> Ended { get => _ended; }
  29. #endregion
  30. public CronInstance()
  31. {
  32. _thread = new Thread(Listen);
  33. _thread.IsBackground = true;
  34. }
  35. /// <summary>打断循环。</summary>
  36. public void Break() => _break = true;
  37. /// <summary>启动线程执行任务。</summary>
  38. public void Start()
  39. {
  40. if (Alive) return;
  41. _thread = new Thread(Listen);
  42. _thread.IsBackground = true;
  43. _thread.Start();
  44. }
  45. int GetInterval()
  46. {
  47. if (_attribute == null) _attribute = new CronAttribute();
  48. return _attribute.Interval;
  49. }
  50. bool GetAlive()
  51. {
  52. if (_thread == null) return false;
  53. if (_thread.IsAlive != true) return false;
  54. if (_thread.ThreadState != ThreadState.Running) return false;
  55. return true;
  56. }
  57. void Listen()
  58. {
  59. if (Type == null) return;
  60. var instance = null as object;
  61. try
  62. {
  63. instance = Activator.CreateInstance(Type);
  64. }
  65. catch (Exception exception)
  66. {
  67. Log(Type.FullName, exception.GetType().FullName, exception.Message);
  68. }
  69. RuntimeUtility.Dispose(instance);
  70. _thread = null;
  71. }
  72. void Log(params object[] content) => _logger.Text(Type.FullName, content);
  73. }
  74. }