/// <summary> /// 设置单一Timer /// </summary> /// <param name="playerSid">palyer ID</param> /// <param name="period">timerPair limit单位:毫秒</param> /// <param name="messageID">message id</param> /// <param name="objData">message data</param> public Int64 SetPlayerContextTimerOneShoot(UInt64 playerSid, Int32 period, Int32 int32Data, Int64 int64Data, Object objData) { if (period < 100) { return(Int64.MinValue); } if (1 != m_state) { return(Int64.MinValue); } // 设置第一次调用时间 Int64 nextCallTime = DateTime.Now.Ticks + (Int64)period * 10000; // 获取该循环Timer唯一ID Int64 timerId = Interlocked.Increment(ref m_timerIdGenerator); // 创建该Player Timer PlayerTimerNode playerTimerNode = new PlayerTimerNode(timerId, nextCallTime, playerSid, int32Data, int64Data, objData); // 尝试添加 Boolean bRet = m_playerCtxTimers.TryAdd(timerId, playerTimerNode); if (!bRet) { throw new Exception("fail to TryAdd timerPair in _playerCtxTimers timerid = " + timerId.ToString()); } return(timerId); }
/// <summary> /// Palyer Timer工作 /// </summary> /// <param name="cancelToken">控制取消对象</param> /// <returns></returns> private async Task PlayerCtxTimerWorkerProc(CancellationToken cancelToken) { // 检查工作状态 if (1 != m_state) { return; } try { //Int64 currentTimeTick = 0; // 没有收到取消请求时 while (!cancelToken.IsCancellationRequested) { //// 获取开始时间毫秒 //currentTimeTick = DateTime.Now.Ticks; //// 用当前时间秒查询循环容器 //IEnumerable<KeyValuePair<Int64, PlayerTimerNode>> query = // m_playerCtxTimers.Where(timer => timer.Value.m_nextCallTime <= currentTimeTick); // 有满足条件的作timer call处理以及删除 foreach (KeyValuePair <Int64, PlayerTimerNode> timerPair in GetTriggerableTimerNodeList()) { // 先删除 PlayerTimerNode playerTimer = null; m_playerCtxTimers.TryRemove(timerPair.Key, out playerTimer); if (playerTimer == null) { continue; } // 查找目标playerctx IManagedContext playerCtx = m_playerCtxManager.FindPlayerContextBySid(playerTimer.m_playerSid); if (playerCtx == null) { continue; } // 发送msg PlayerTimerMessage message = new PlayerTimerMessage(playerTimer.m_int32Data, playerTimer.m_int64Data, playerTimer.m_objData); playerCtx.PostLocalMessage(message); } // 每500毫秒轮询一次 await Task.Delay(500); } Log.Debug("TimerManager::PlayerCtxTimerWorkerProc stop"); } catch (Exception ex) { Log.Debug("TimerManager::PlayerCtxTimerWorkerProc catch Execption: " + ex.ToString()); } }