Alarm.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. namespace XGame.Framework.Time
  3. {
  4. public class Alarm : IAlarm, IDisposable
  5. {
  6. public enum AlarmRunState : sbyte
  7. {
  8. None,
  9. Running,
  10. Stoped,
  11. Finished,
  12. }
  13. private long _triggerTimeStamp;
  14. private long _curTimeStamp;
  15. private Action _action;
  16. private AlarmRunState _runState;
  17. public AlarmRunState State
  18. {
  19. get => _runState;
  20. private set
  21. {
  22. _runState = value;
  23. if (value is AlarmRunState.Stoped or AlarmRunState.Finished)
  24. {
  25. try
  26. {
  27. Listener?.OnCompleted(this);
  28. }
  29. catch (Exception ex)
  30. {
  31. Log.Exception($"闹钟事件监听执行异常.", ex);
  32. }
  33. Listener = null;
  34. }
  35. }
  36. }
  37. public ITimeListener<IAlarm> Listener { get; set; }
  38. public Alarm(Action action, long curTimeStamp, long triggerTimeStamp)
  39. {
  40. #if UNITY_EDITOR
  41. UnityEngine.Assertions.Assert.IsTrue(triggerTimeStamp > curTimeStamp, "设置闹钟触发时间不能小于或者等于当前时间");
  42. #endif
  43. _triggerTimeStamp = triggerTimeStamp;
  44. _curTimeStamp = curTimeStamp;
  45. _action = action;
  46. State = AlarmRunState.Running;
  47. }
  48. public void SetTime(long timestamp)
  49. {
  50. if (State == AlarmRunState.Running)
  51. {
  52. _curTimeStamp = timestamp;
  53. }
  54. }
  55. public void Cancel()
  56. {
  57. State = AlarmRunState.Stoped;
  58. _action = null;
  59. }
  60. public bool Update(int elapse)
  61. {
  62. if (State != AlarmRunState.Running)
  63. {
  64. return true;
  65. }
  66. _curTimeStamp += elapse;
  67. if (_curTimeStamp >= _triggerTimeStamp)
  68. {
  69. State = AlarmRunState.Finished;
  70. try
  71. {
  72. _action?.Invoke();
  73. }
  74. catch (Exception e)
  75. {
  76. Log.Exception("闹钟回调执行发生异常", e);
  77. //throw new Exception($"闹钟回调执行发生异常:{e}");
  78. }
  79. return true;
  80. }
  81. return false;
  82. }
  83. public void Dispose()
  84. {
  85. _action = null;
  86. Listener = null;
  87. }
  88. }
  89. }