TimerComponent.cs 10 KB

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