public static async ETTask <bool> WaitTillAsync(this TimerComponent self, long tillTime, ETCancellationToken cancellationToken = null) { if (self.timeNow >= tillTime) { return(true); } ETTask <bool> tcs = ETTask <bool> .Create(true); TimerAction timer = self.AddChild <TimerAction, TimerClass, long, int, object>(TimerClass.OnceWaitTimer, tillTime - self.timeNow, 0, tcs, true); self.AddTimer(tillTime, timer); long timerId = timer.Id; void CancelAction() { if (self.Remove(timerId)) { tcs.SetResult(false); } } bool ret; try { cancellationToken?.Add(CancelAction); ret = await tcs; } finally { cancellationToken?.Remove(CancelAction); } return(ret); }
// 用这个优点是可以热更,缺点是回调式的写法,逻辑不连贯。WaitTillAsync不能热更,优点是逻辑连贯。 // wait时间短并且逻辑需要连贯的建议WaitTillAsync // wait时间长不需要逻辑连贯的建议用NewOnceTimer public static long NewOnceTimer(this TimerComponent self, long tillTime, int type, object args) { if (tillTime < TimeHelper.ServerNow()) { Log.Warning($"new once time too small: {tillTime}"); } TimerAction timer = self.AddChild <TimerAction, TimerClass, long, int, object>(TimerClass.OnceTimer, tillTime, type, args, true); self.AddTimer(tillTime, timer); return(timer.Id); }
/// <summary> /// 创建一个RepeatedTimer /// </summary> private static long NewRepeatedTimerInner(this TimerComponent self, long time, int type, object args) { #if NOT_UNITY if (time < 100) { throw new Exception($"repeated timer < 100, timerType: time: {time}"); } #endif long tillTime = TimeHelper.ServerNow() + time; TimerAction timer = self.AddChild <TimerAction, TimerClass, long, int, object>(TimerClass.RepeatedTimer, time, type, args, true); // 每帧执行的不用加到timerId中,防止遍历 self.AddTimer(tillTime, timer); return(timer.Id); }