Clock.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. namespace XGame.Framework.Time
  3. {
  4. public class Clock : IClock
  5. {
  6. private AlarmRepository _clientAlarmRepo;
  7. private AlarmRepository _serverAlarmRepo;
  8. private TimerRepository _timerRepo;
  9. public Clock(long timeStamp)
  10. {
  11. var realTime = UnityEngine.Time.realtimeSinceStartup;
  12. _clientAlarmRepo = new AlarmRepository()
  13. {
  14. time = new TimeStamp()
  15. {
  16. realtimeSinceStartup = realTime,
  17. timeStamp = timeStamp
  18. }
  19. };
  20. _serverAlarmRepo = new AlarmRepository()
  21. {
  22. time = new TimeStamp()
  23. {
  24. realtimeSinceStartup = realTime,
  25. timeStamp = timeStamp
  26. }
  27. };
  28. _timerRepo = new TimerRepository();
  29. }
  30. private AlarmRepository GetAlarmRepository(ClockType clockTyp = ClockType.Server)
  31. {
  32. return clockTyp == ClockType.Server ? _serverAlarmRepo : _clientAlarmRepo;
  33. }
  34. public void SetTime(long timestamp, ClockType clockTyp = ClockType.Server)
  35. {
  36. GetAlarmRepository(clockTyp).SetTime(timestamp);
  37. }
  38. public long GetNowTime(ClockType clockTyp = ClockType.Server)
  39. {
  40. var alarmTime = GetAlarmRepository(clockTyp).time;
  41. return alarmTime.timeStamp + (long)((UnityEngine.Time.realtimeSinceStartup - alarmTime.realtimeSinceStartup) * 1000);
  42. }
  43. public IAlarm AddAlarm(long triggerTimestamp, Action action, ClockType clockTyp = ClockType.Server)
  44. {
  45. return GetAlarmRepository(clockTyp).AddAlarm(action, GetNowTime(clockTyp), triggerTimestamp);
  46. }
  47. public ITimer AddDelayTimer(int delay, Action action)
  48. {
  49. return _timerRepo.AddDelayTimer(delay, action);
  50. }
  51. public ITimer AddLooperTimer(int delay, int interval, Action action)
  52. {
  53. return _timerRepo.AddLooperTimer(delay, interval, action);
  54. }
  55. public ITimer AddLooperTimer(int delay, int interval, Action<int> action)
  56. {
  57. return _timerRepo.AddLooperTimer(delay, interval, action);
  58. }
  59. public ITimer AddLooperTimer(int delay, int interval, int loopTime, Action action)
  60. {
  61. return _timerRepo.AddLooperTimer(delay, interval, loopTime, action);
  62. }
  63. public ITimer AddLooperTimer(int delay, int interval, int loopTime, Action<int> action)
  64. {
  65. return _timerRepo.AddLooperTimer(delay, interval, loopTime, action);
  66. }
  67. public void Update(int millisecond)
  68. {
  69. _clientAlarmRepo.ClockUpdate(millisecond);
  70. _serverAlarmRepo.ClockUpdate(millisecond);
  71. _timerRepo.ClockUpdate(millisecond);
  72. }
  73. public void Dispose()
  74. {
  75. _clientAlarmRepo.Dispose();
  76. _serverAlarmRepo.Dispose();
  77. _timerRepo.Dispose();
  78. }
  79. }
  80. }