TimerComponent.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. using System.Collections.Generic;
  2. namespace ET
  3. {
  4. public enum TimerClass
  5. {
  6. None,
  7. OnceTimer,
  8. OnceWaitTimer,
  9. RepeatedTimer,
  10. }
  11. public class TimerAction
  12. {
  13. public static TimerAction Create(long id, TimerClass timerClass, long startTime, long time, int type, object obj)
  14. {
  15. TimerAction timerAction = ObjectPool.Instance.Fetch<TimerAction>();
  16. timerAction.Id = id;
  17. timerAction.TimerClass = timerClass;
  18. timerAction.StartTime = startTime;
  19. timerAction.Object = obj;
  20. timerAction.Time = time;
  21. timerAction.Type = type;
  22. return timerAction;
  23. }
  24. public long Id;
  25. public TimerClass TimerClass;
  26. public object Object;
  27. public long StartTime;
  28. public long Time;
  29. public int Type;
  30. public void Recycle()
  31. {
  32. this.Id = 0;
  33. this.Object = null;
  34. this.StartTime = 0;
  35. this.Time = 0;
  36. this.TimerClass = TimerClass.None;
  37. this.Type = 0;
  38. ObjectPool.Instance.Recycle(this);
  39. }
  40. }
  41. public struct TimerCallback
  42. {
  43. public object Args;
  44. }
  45. public class TimerComponent: Singleton<TimerComponent>, ISingletonUpdate
  46. {
  47. /// <summary>
  48. /// key: time, value: timer id
  49. /// </summary>
  50. private readonly MultiMap<long, long> TimeId = new();
  51. private readonly Queue<long> timeOutTime = new();
  52. private readonly Queue<long> timeOutTimerIds = new();
  53. private readonly Dictionary<long, TimerAction> timerActions = new();
  54. private long idGenerator;
  55. // 记录最小时间,不用每次都去MultiMap取第一个值
  56. private long minTime = long.MaxValue;
  57. private long GetId()
  58. {
  59. return ++this.idGenerator;
  60. }
  61. private static long GetNow()
  62. {
  63. return TimeHelper.ClientFrameTime();
  64. }
  65. public void Update(int timeMS)
  66. {
  67. if (this.TimeId.Count == 0)
  68. {
  69. return;
  70. }
  71. long timeNow = GetNow();
  72. if (timeNow < this.minTime)
  73. {
  74. return;
  75. }
  76. foreach (KeyValuePair<long, List<long>> kv in this.TimeId)
  77. {
  78. long k = kv.Key;
  79. if (k > timeNow)
  80. {
  81. this.minTime = k;
  82. break;
  83. }
  84. this.timeOutTime.Enqueue(k);
  85. }
  86. while (this.timeOutTime.Count > 0)
  87. {
  88. long time = this.timeOutTime.Dequeue();
  89. var list = this.TimeId[time];
  90. for (int i = 0; i < list.Count; ++i)
  91. {
  92. long timerId = list[i];
  93. this.timeOutTimerIds.Enqueue(timerId);
  94. }
  95. this.TimeId.Remove(time);
  96. }
  97. while (this.timeOutTimerIds.Count > 0)
  98. {
  99. long timerId = this.timeOutTimerIds.Dequeue();
  100. if (!this.timerActions.Remove(timerId, out TimerAction timerAction))
  101. {
  102. continue;
  103. }
  104. this.Run(timerAction);
  105. }
  106. }
  107. private void Run(TimerAction timerAction)
  108. {
  109. switch (timerAction.TimerClass)
  110. {
  111. case TimerClass.OnceTimer:
  112. {
  113. EventSystem.Instance.Invoke(timerAction.Type, new TimerCallback() { Args = timerAction.Object });
  114. timerAction.Recycle();
  115. break;
  116. }
  117. case TimerClass.OnceWaitTimer:
  118. {
  119. ETTask tcs = timerAction.Object as ETTask;
  120. tcs.SetResult();
  121. timerAction.Recycle();
  122. break;
  123. }
  124. case TimerClass.RepeatedTimer:
  125. {
  126. long timeNow = GetNow();
  127. timerAction.StartTime = timeNow;
  128. this.AddTimer(timerAction);
  129. EventSystem.Instance.Invoke(timerAction.Type, new TimerCallback() { Args = timerAction.Object });
  130. break;
  131. }
  132. }
  133. }
  134. private void AddTimer(TimerAction timer)
  135. {
  136. long tillTime = timer.StartTime + timer.Time;
  137. this.TimeId.Add(tillTime, timer.Id);
  138. this.timerActions.Add(timer.Id, timer);
  139. if (tillTime < this.minTime)
  140. {
  141. this.minTime = tillTime;
  142. }
  143. }
  144. public bool Remove(ref long id)
  145. {
  146. long i = id;
  147. id = 0;
  148. return this.Remove(i);
  149. }
  150. private bool Remove(long id)
  151. {
  152. if (id == 0)
  153. {
  154. return false;
  155. }
  156. if (!this.timerActions.Remove(id, out TimerAction timerAction))
  157. {
  158. return false;
  159. }
  160. timerAction.Recycle();
  161. return true;
  162. }
  163. public async ETTask WaitTillAsync(long tillTime, ETCancellationToken cancellationToken = null)
  164. {
  165. long timeNow = GetNow();
  166. if (timeNow >= tillTime)
  167. {
  168. return;
  169. }
  170. ETTask tcs = ETTask.Create(true);
  171. TimerAction timer = TimerAction.Create(this.GetId(), TimerClass.OnceWaitTimer, timeNow, tillTime - timeNow, 0, tcs);
  172. this.AddTimer(timer);
  173. long timerId = timer.Id;
  174. void CancelAction()
  175. {
  176. if (this.Remove(timerId))
  177. {
  178. tcs.SetResult();
  179. }
  180. }
  181. try
  182. {
  183. cancellationToken?.Add(CancelAction);
  184. await tcs;
  185. }
  186. finally
  187. {
  188. cancellationToken?.Remove(CancelAction);
  189. }
  190. }
  191. public async ETTask WaitFrameAsync(ETCancellationToken cancellationToken = null)
  192. {
  193. await this.WaitAsync(1, cancellationToken);
  194. }
  195. public async ETTask WaitAsync(long time, ETCancellationToken cancellationToken = null)
  196. {
  197. if (time == 0)
  198. {
  199. return;
  200. }
  201. long timeNow = GetNow();
  202. ETTask tcs = ETTask.Create(true);
  203. TimerAction timer = TimerAction.Create(this.GetId(), TimerClass.OnceWaitTimer, timeNow, time, 0, tcs);
  204. this.AddTimer(timer);
  205. long timerId = timer.Id;
  206. void CancelAction()
  207. {
  208. if (this.Remove(timerId))
  209. {
  210. tcs.SetResult();
  211. }
  212. }
  213. try
  214. {
  215. cancellationToken?.Add(CancelAction);
  216. await tcs;
  217. }
  218. finally
  219. {
  220. cancellationToken?.Remove(CancelAction);
  221. }
  222. }
  223. // 用这个优点是可以热更,缺点是回调式的写法,逻辑不连贯。WaitTillAsync不能热更,优点是逻辑连贯。
  224. // wait时间短并且逻辑需要连贯的建议WaitTillAsync
  225. // wait时间长不需要逻辑连贯的建议用NewOnceTimer
  226. public long NewOnceTimer(long tillTime, int type, object args)
  227. {
  228. long timeNow = GetNow();
  229. if (tillTime < timeNow)
  230. {
  231. Log.Error($"new once time too small: {tillTime}");
  232. }
  233. TimerAction timer = TimerAction.Create(this.GetId(), TimerClass.OnceTimer, timeNow, tillTime - timeNow, type, args);
  234. this.AddTimer(timer);
  235. return timer.Id;
  236. }
  237. public long NewFrameTimer(int type, object args)
  238. {
  239. #if DOTNET
  240. return this.NewRepeatedTimerInner(100, type, args);
  241. #else
  242. return this.NewRepeatedTimerInner(0, type, args);
  243. #endif
  244. }
  245. /// <summary>
  246. /// 创建一个RepeatedTimer
  247. /// </summary>
  248. private long NewRepeatedTimerInner(long time, int type, object args)
  249. {
  250. #if DOTNET
  251. if (time < 100)
  252. {
  253. throw new Exception($"repeated timer < 100, timerType: time: {time}");
  254. }
  255. #endif
  256. long timeNow = GetNow();
  257. TimerAction timer = TimerAction.Create(this.GetId(), TimerClass.RepeatedTimer, timeNow, time, type, args);
  258. // 每帧执行的不用加到timerId中,防止遍历
  259. this.AddTimer(timer);
  260. return timer.Id;
  261. }
  262. public long NewRepeatedTimer(long time, int type, object args)
  263. {
  264. if (time < 100)
  265. {
  266. Log.Error($"time too small: {time}");
  267. return 0;
  268. }
  269. return this.NewRepeatedTimerInner(time, type, args);
  270. }
  271. }
  272. }