Alarm.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 Alarm(Action action, long curTimeStamp, long triggerTimeStamp)
  18. {
  19. #if UNITY_EDITOR
  20. UnityEngine.Assertions.Assert.IsTrue(triggerTimeStamp > curTimeStamp, "设置闹钟触发时间不能小于或者等于当前时间");
  21. #endif
  22. _triggerTimeStamp = triggerTimeStamp;
  23. _curTimeStamp = curTimeStamp;
  24. _action = action;
  25. _runState = AlarmRunState.Running;
  26. }
  27. public void SetTime(long timestamp)
  28. {
  29. if (_runState == AlarmRunState.Running)
  30. {
  31. _curTimeStamp = timestamp;
  32. }
  33. }
  34. public void Cancel()
  35. {
  36. _runState = AlarmRunState.Stoped;
  37. _action = null;
  38. }
  39. public bool Update(int elapse)
  40. {
  41. if (_runState != AlarmRunState.Running)
  42. {
  43. return true;
  44. }
  45. _curTimeStamp += elapse;
  46. if (_curTimeStamp >= _triggerTimeStamp)
  47. {
  48. _runState = AlarmRunState.Finished;
  49. try
  50. {
  51. _action?.Invoke();
  52. }
  53. catch (Exception e)
  54. {
  55. Log.Exception("闹钟回调执行发生异常", e);
  56. //throw new Exception($"闹钟回调执行发生异常:{e}");
  57. }
  58. return true;
  59. }
  60. return false;
  61. }
  62. public void Dispose()
  63. {
  64. _action = null;
  65. }
  66. }
  67. }