TimerComponent.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace ET
  5. {
  6. public interface ITimer
  7. {
  8. void Run(bool isTimeout);
  9. }
  10. public class OnceWaitTimerAwakeSystem : AwakeSystem<OnceWaitTimer, ETTaskCompletionSource<bool>>
  11. {
  12. public override void Awake(OnceWaitTimer self, ETTaskCompletionSource<bool> callback)
  13. {
  14. self.Callback = callback;
  15. }
  16. }
  17. public class OnceWaitTimer: Entity, ITimer
  18. {
  19. public ETTaskCompletionSource<bool> Callback { get; set; }
  20. public void Run(bool isTimeout)
  21. {
  22. ETTaskCompletionSource<bool> tcs = this.Callback;
  23. this.GetParent<TimerComponent>().Remove(this.Id);
  24. tcs.SetResult(isTimeout);
  25. }
  26. }
  27. public class OnceTimerAwakeSystem : AwakeSystem<OnceTimer, Action<bool>>
  28. {
  29. public override void Awake(OnceTimer self, Action<bool> callback)
  30. {
  31. self.Callback = callback;
  32. }
  33. }
  34. public class OnceTimer: Entity, ITimer
  35. {
  36. public Action<bool> Callback { get; set; }
  37. public void Run(bool isTimeout)
  38. {
  39. try
  40. {
  41. this.Callback.Invoke(isTimeout);
  42. }
  43. catch (Exception e)
  44. {
  45. Log.Error(e);
  46. }
  47. }
  48. }
  49. public class RepeatedTimerAwakeSystem : AwakeSystem<RepeatedTimer, long, Action<bool>>
  50. {
  51. public override void Awake(RepeatedTimer self, long repeatedTime, Action<bool> callback)
  52. {
  53. self.Awake(repeatedTime, callback);
  54. }
  55. }
  56. public class RepeatedTimer: Entity, ITimer
  57. {
  58. public void Awake(long repeatedTime, Action<bool> callback)
  59. {
  60. this.StartTime = TimeHelper.Now();
  61. this.RepeatedTime = repeatedTime;
  62. this.Callback = callback;
  63. this.Count = 1;
  64. }
  65. private long StartTime { get; set; }
  66. private long RepeatedTime { get; set; }
  67. // 下次一是第几次触发
  68. private int Count { get; set; }
  69. public Action<bool> Callback { private get; set; }
  70. public void Run(bool isTimeout)
  71. {
  72. ++this.Count;
  73. TimerComponent timerComponent = this.GetParent<TimerComponent>();
  74. long tillTime = this.StartTime + this.RepeatedTime * this.Count;
  75. timerComponent.AddToTimeId(tillTime, this.Id);
  76. try
  77. {
  78. this.Callback?.Invoke(isTimeout);
  79. }
  80. catch (Exception e)
  81. {
  82. Log.Error(e);
  83. }
  84. }
  85. public override void Dispose()
  86. {
  87. if (this.IsDisposed)
  88. {
  89. return;
  90. }
  91. long id = this.Id;
  92. if (id == 0)
  93. {
  94. Log.Error($"RepeatedTimer可能多次释放了");
  95. return;
  96. }
  97. base.Dispose();
  98. this.StartTime = 0;
  99. this.RepeatedTime = 0;
  100. this.Callback = null;
  101. this.Count = 0;
  102. }
  103. }
  104. public class TimerComponentAwakeSystem : AwakeSystem<TimerComponent>
  105. {
  106. public override void Awake(TimerComponent self)
  107. {
  108. TimerComponent.Instance = self;
  109. }
  110. }
  111. public class TimerComponentUpdateSystem : UpdateSystem<TimerComponent>
  112. {
  113. public override void Update(TimerComponent self)
  114. {
  115. self.Update();
  116. }
  117. }
  118. public class TimerComponent : Entity
  119. {
  120. public static TimerComponent Instance { get; set; }
  121. private readonly Dictionary<long, ITimer> timers = new Dictionary<long, ITimer>();
  122. /// <summary>
  123. /// key: time, value: timer id
  124. /// </summary>
  125. public readonly MultiMap<long, long> TimeId = new MultiMap<long, long>();
  126. private readonly Queue<long> timeOutTime = new Queue<long>();
  127. private readonly Queue<long> timeOutTimerIds = new Queue<long>();
  128. // 记录最小时间,不用每次都去MultiMap取第一个值
  129. private long minTime;
  130. public void Update()
  131. {
  132. if (this.TimeId.Count == 0)
  133. {
  134. return;
  135. }
  136. long timeNow = TimeHelper.Now();
  137. if (timeNow < this.minTime)
  138. {
  139. return;
  140. }
  141. foreach (KeyValuePair<long, List<long>> kv in this.TimeId.GetDictionary())
  142. {
  143. long k = kv.Key;
  144. if (k > timeNow)
  145. {
  146. minTime = k;
  147. break;
  148. }
  149. this.timeOutTime.Enqueue(k);
  150. }
  151. while(this.timeOutTime.Count > 0)
  152. {
  153. long time = this.timeOutTime.Dequeue();
  154. foreach(long timerId in this.TimeId[time])
  155. {
  156. this.timeOutTimerIds.Enqueue(timerId);
  157. }
  158. this.TimeId.Remove(time);
  159. }
  160. while(this.timeOutTimerIds.Count > 0)
  161. {
  162. long timerId = this.timeOutTimerIds.Dequeue();
  163. ITimer timer;
  164. if (!this.timers.TryGetValue(timerId, out timer))
  165. {
  166. continue;
  167. }
  168. timer.Run(true);
  169. }
  170. }
  171. public async ETTask<bool> WaitTillAsync(long tillTime, ETCancellationToken cancellationToken)
  172. {
  173. if (TimeHelper.Now() > tillTime)
  174. {
  175. return true;
  176. }
  177. ETTaskCompletionSource<bool> tcs = new ETTaskCompletionSource<bool>();
  178. OnceWaitTimer timer = EntityFactory.CreateWithParent<OnceWaitTimer, ETTaskCompletionSource<bool>>(this, tcs);
  179. this.timers[timer.Id] = timer;
  180. AddToTimeId(tillTime, timer.Id);
  181. long instanceId = timer.InstanceId;
  182. cancellationToken.Register(() =>
  183. {
  184. if (instanceId != timer.InstanceId)
  185. {
  186. return;
  187. }
  188. timer.Run(false);
  189. this.Remove(timer.Id);
  190. });
  191. return await tcs.Task;
  192. }
  193. public async ETTask<bool> WaitTillAsync(long tillTime)
  194. {
  195. if (TimeHelper.Now() > tillTime)
  196. {
  197. return true;
  198. }
  199. ETTaskCompletionSource<bool> tcs = new ETTaskCompletionSource<bool>();
  200. OnceWaitTimer timer = EntityFactory.CreateWithParent<OnceWaitTimer, ETTaskCompletionSource<bool>>(this, tcs);
  201. this.timers[timer.Id] = timer;
  202. AddToTimeId(tillTime, timer.Id);
  203. return await tcs.Task;
  204. }
  205. public async ETTask<bool> WaitAsync(long time, ETCancellationToken cancellationToken)
  206. {
  207. long tillTime = TimeHelper.Now() + time;
  208. if (TimeHelper.Now() > tillTime)
  209. {
  210. return true;
  211. }
  212. ETTaskCompletionSource<bool> tcs = new ETTaskCompletionSource<bool>();
  213. OnceWaitTimer timer = EntityFactory.CreateWithParent<OnceWaitTimer, ETTaskCompletionSource<bool>>(this, tcs);
  214. this.timers[timer.Id] = timer;
  215. AddToTimeId(tillTime, timer.Id);
  216. long instanceId = timer.InstanceId;
  217. cancellationToken.Register(() =>
  218. {
  219. if (instanceId != timer.InstanceId)
  220. {
  221. return;
  222. }
  223. timer.Run(false);
  224. this.Remove(timer.Id);
  225. });
  226. return await tcs.Task;
  227. }
  228. public async ETTask<bool> WaitAsync(long time)
  229. {
  230. long tillTime = TimeHelper.Now() + time;
  231. ETTaskCompletionSource<bool> tcs = new ETTaskCompletionSource<bool>();
  232. OnceWaitTimer timer = EntityFactory.CreateWithParent<OnceWaitTimer, ETTaskCompletionSource<bool>>(this, tcs);
  233. this.timers[timer.Id] = timer;
  234. AddToTimeId(tillTime, timer.Id);
  235. return await tcs.Task;
  236. }
  237. /// <summary>
  238. /// 创建一个RepeatedTimer
  239. /// </summary>
  240. /// <param name="time"></param>
  241. /// <param name="action"></param>
  242. /// <returns></returns>
  243. public long NewRepeatedTimer(long time, Action<bool> action)
  244. {
  245. if (time < 30)
  246. {
  247. throw new Exception($"repeated time < 30");
  248. }
  249. long tillTime = TimeHelper.Now() + time;
  250. RepeatedTimer timer = EntityFactory.CreateWithParent<RepeatedTimer, long, Action<bool>>(this, time, action);
  251. this.timers[timer.Id] = timer;
  252. AddToTimeId(tillTime, timer.Id);
  253. return timer.Id;
  254. }
  255. public RepeatedTimer GetRepeatedTimer(long id)
  256. {
  257. if (!this.timers.TryGetValue(id, out ITimer timer))
  258. {
  259. return null;
  260. }
  261. return timer as RepeatedTimer;
  262. }
  263. public void Remove(long id)
  264. {
  265. if (id == 0)
  266. {
  267. return;
  268. }
  269. ITimer timer;
  270. if (!this.timers.TryGetValue(id, out timer))
  271. {
  272. return;
  273. }
  274. this.timers.Remove(id);
  275. (timer as IDisposable)?.Dispose();
  276. }
  277. public long NewOnceTimer(long tillTime, Action action)
  278. {
  279. OnceTimer timer = EntityFactory.CreateWithParent<OnceTimer, Action>(this, action);
  280. this.timers[timer.Id] = timer;
  281. AddToTimeId(tillTime, timer.Id);
  282. return timer.Id;
  283. }
  284. public OnceTimer GetOnceTimer(long id)
  285. {
  286. if (!this.timers.TryGetValue(id, out ITimer timer))
  287. {
  288. return null;
  289. }
  290. return timer as OnceTimer;
  291. }
  292. public void AddToTimeId(long tillTime, long id)
  293. {
  294. this.TimeId.Add(tillTime, id);
  295. if (tillTime < this.minTime)
  296. {
  297. this.minTime = tillTime;
  298. }
  299. }
  300. }
  301. }