AlarmRepository.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. namespace XGame.Framework.Time
  4. {
  5. /// <summary>
  6. /// 闹钟仓储
  7. /// </summary>
  8. public class AlarmRepository : IClockTick, ICalibrator, IDisposable
  9. {
  10. private List<Alarm> _aliveAlarms = new List<Alarm>();
  11. public TimeStamp time;
  12. internal IAlarm AddAlarm(Action action, long curTimeStamp, long triggerTimeStamp)
  13. {
  14. var alarm = new Alarm(action, curTimeStamp, triggerTimeStamp);
  15. _aliveAlarms.Add(alarm);
  16. return alarm;
  17. }
  18. public void SetTime(long timestamp)
  19. {
  20. time.timeStamp = timestamp;
  21. time.realtimeSinceStartup = UnityEngine.Time.realtimeSinceStartup;
  22. for (int i = 0; i < _aliveAlarms.Count; i++)
  23. {
  24. if (_aliveAlarms[i] is ICalibrator calib)
  25. {
  26. calib.SetTime(timestamp);
  27. }
  28. }
  29. }
  30. public void ClockUpdate(int millisecond)
  31. {
  32. // 客户端定时器数量较少不考虑时间轮优化
  33. for (int i = _aliveAlarms.Count - 1; i >= 0; --i)
  34. {
  35. if(_aliveAlarms[i].Update(millisecond))
  36. {
  37. _aliveAlarms.RemoveAt(i);
  38. }
  39. }
  40. }
  41. public void Dispose()
  42. {
  43. time = default;
  44. foreach (var item in _aliveAlarms)
  45. {
  46. item.Dispose();
  47. }
  48. _aliveAlarms.Clear();
  49. }
  50. }
  51. }