/// <summary> /// 设置循环Timer /// </summary> /// <param name="period">循环间隔时间,单位:毫秒</param> /// <param name="callBack">回调函数</param> /// <param name="key">回调参数</param> /// <returns>该循环Timer唯一ID Int64.MinValue表示失败</returns> public Int64 SetLoopTimer(Int32 period, OnBattleTimerCallBack callBack, Int32 int32Data = 0, Int64 int64Data = 0, Object objData = null) { if (period < 10 || m_state != 1) { return(Int64.MinValue); } // 获取该循环Timer唯一ID Int64 timerId = Interlocked.Increment(ref m_timerIdGenerator); CancellationTokenSource cts = new CancellationTokenSource(); // 创建该循环Timer BattleTimerNode timerNode = new BattleTimerNode(timerId, period, cts, callBack); // 创建该Timer循环任务 timerNode.m_task = TimerWorkerProc(cts.Token, timerNode); // 尝试添加 Boolean bRet = m_loopTimers.TryAdd(timerId, timerNode); if (!bRet) { throw new Exception("fail to TryAdd timerPair in _loopTimers timerid = " + timerId.ToString()); } // _log.InfoFormat("SetLoopTimer {0} {1} is start", timerId, period.ToString()); return(timerId); }
/// <summary> /// 单个TimerNode的循环Timer工作 /// </summary> /// <param name="cancelToken">控制取消对象</param> /// <param name="timerNode">单个TimerNode对象</param> /// <returns></returns> private async Task TimerWorkerProc(CancellationToken cancelToken, BattleTimerNode timerNode) { // 检查工作状态 if (1 != m_state) { return; } try { Int64 currentTimeTick = 0; Int64 delayMillSeconds = 0; // 没有收到取消请求时 while (!cancelToken.IsCancellationRequested) { // 获取处理开始时间毫微秒 currentTimeTick = DateTime.Now.Ticks; // 第一次设置时间 if (timerNode.m_nextCallTime == 0) { timerNode.m_nextCallTime = currentTimeTick + timerNode.m_period * 10000;//*10000 转换成tick单位 } if (currentTimeTick >= timerNode.m_nextCallTime) { try { timerNode.MakeTimerCall(); } catch (Exception ex) { Log.Error("BattleTimerManager::TimerWorkerProc catch Exception: " + ex.ToString()); } timerNode.m_nextCallTime = currentTimeTick + timerNode.m_period * 10000; } // 获取处理结束时间毫秒 delayMillSeconds = timerNode.m_nextCallTime - DateTime.Now.Ticks; if (delayMillSeconds > 10000000) // 大于1秒休息一秒 { await Task.Delay(1000); } else if (delayMillSeconds > 10000)// 否则休息指定时间 { await Task.Delay((int)delayMillSeconds / 10000); } } Log.Info("GameTimerManager::TimerWorkerProc stop timerid=" + timerNode.m_id); return; } catch (Exception ex) { Log.Error("TimerManager::TimerWorkerProc catch Exception1: " + ex.ToString()); } }
/// <summary> /// 移除一个循环Timer /// </summary> /// <param name="id">该循环Timer唯一ID</param> /// <returns>成功:该循环Timer唯一ID,失败:负值</returns> public Boolean UnsetLoopTimer(Int64 timerId) { BattleTimerNode timerNode = null; // 先从容器内移除 Boolean ret = m_loopTimers.TryRemove(timerId, out timerNode); // 对timer执行cancel操作 timerNode?.CancelTask(); return(ret); }