private void ExecuteTasks() { while (true) { IPendingTask task = null; try { task = DequeueNextTask(_deactivationThreshold); if (task == null) { break; } task.Execute(); } catch (Exception e) { if (_exceptions != null) { _exceptions.Add(e); } Log.ErrorFormat("Caught exception while executing task '{0}': {1}", task, e); } } }
public void Start(int actualizationPeriodMs) { _actualizeTask = _taskScheduler.ScheduleOnInterval(async() => { //actualize await Actualize(_statsProvider.GetPeerCount()); }, 0, actualizationPeriodMs); }
public void Start(int queueDepth = 100, int clearQueuesIntervalMs = 1000, int trackIntervalMs = 1000) { _queueDepth = queueDepth; _clearQueuesIntervalMs = clearQueuesIntervalMs; _trackIntervalMs = trackIntervalMs; _clearTask = _taskScheduler.ScheduleOnInterval(CutQueues, 0, _clearQueuesIntervalMs, true); }
public void Connect(string address, int port) { //switch Sockets implementation.BEGIN //_socket = new HazelSock(_logger); _socket = new LiteNetSock(_logger); //switch sockets implementation.END _socket.OnPacketReceived += (endPoint, dataPacket, release) => { _onPackageReceived(dataPacket, release); //todo if using hazel then this part should be considered in releaseAction param // _socket.ReturnBufferToPool(dataPacket.Buffer); }; _socket.OnDisconnected += OnDisconnected; _socket.OnConnected += ep => { OnConnectedToServer?.Invoke(); }; _ep = GetIPEndPointFromHostName(address, port, false); // new IPEndPoint(IPAddress.Parse(address), port); _socket.Connect(_ep); _connected = true; _isTicking = false; //Send(new ConnectedEvent()); _socketTickTask = _taskScheduler.ScheduleOnInterval(() => { lock (_stateSync) { if (!_connected) { return; } lock (_isTickingMutex) { if (_isTicking) { return; } _isTicking = true; } try { _socket.Tick(); } catch (Exception ex) { _logger.Error($"Socket tick error: {ex}"); } finally { lock (_isTickingMutex) _isTicking = false; } } }, 0, 10); _logger?.Debug($"Receive loop started"); }
public void Start(bool shortLiving) { if (_sendTaskId != null) { throw new Exception("PacketSender already started"); } //start send _sendTaskId = _taskScheduler.ScheduleOnInterval(Send, 0, _config.SendTickTimeMs, shortLiving); }
private void EnqueueTask(IPendingTask pendingTask, Task task) { _pendingTasks.Enqueue(pendingTask); _pendingTaskCount.Release(1); if (Log.IsDebugEnabled) { Log.DebugFormat("Queueing task '#{0}'", task.Id); } }
//in unity this should be overriden to process messages inside the main thread protected virtual void StartProcessingMessagesLoop() { _pollingTask = _taskScheduler.ScheduleOnInterval(() => { IPacketInfo pack = null; while ((pack = PopNextPacket()) != null) { //launch callback in another thread var pack1 = pack; _taskScheduler.ScheduleOnceOnNow(() => { ClientOnPackageReceived(pack1); }); } }, 0, _pollPackageQueueIntervalMs); }
private void OnJoinRoomResponse(MessageBase message) { _logger.Debug($"JoinRoomResponse received"); var response = message as JoinRoomResponse; if (response == null || response.ResultCode != ResultCode.OK) { if (response == null) { SetAndReportStatus(ClientStatusLegacy.JoiningRoom, _statusCallback, false, "Error casting JoinRoomResponse"); return; } if (response.ResultCode != ResultCode.OK) { SetAndReportStatus(ClientStatusLegacy.JoiningRoom, _statusCallback, false, $"JoinRoomResponse error: {response.ResultCode}"); return; } } SetAndReportStatus(ClientStatusLegacy.InRoom, _statusCallback); //start ping sequence _pingTask = _taskScheduler.ScheduleOnInterval(() => { if (_isPinging) { return; } _isPinging = true; _pingRequestSentOn = DateTime.UtcNow; SendRequest(new PingRequest(), OnPingResponse); //schedule resetting flag _resetPingTask = _taskScheduler.Schedule(() => { _isPinging = false; _rtt = int.MaxValue; }, 2000); }, 0, 1000); }
public void Stop() { _taskScheduler.Dispose(); _sendTaskId = null; foreach (var peer in _peerToPackets.Keys) { if (_peerToPackets.TryRemove(peer, out var q)) { lock (_sync) { while (q.TryDequeue(out var pack)) { pack.Dispose(); } } } } }
public void Remove(IPendingTask task) { var pt = task as PendingTask; if (pt == null) { return; } lock (_listLock) { var pendingTask = _tasks.FirstOrDefault(t => t == pt); if (pendingTask == null) { return; } _logger?.Debug($"Removing {pendingTask.GetActionName()}"); pendingTask.Dispose(); _tasks.Remove(pt); } }
private void StartProcessingMessagesLoop() { _pollingTask = _taskScheduler.ScheduleOnInterval(() => { IPacketInfo pack = null; while ((pack = PopNextPacket()) != null) { //launch callback in another thread var pack1 = pack; _taskScheduler.ScheduleOnceOnNow(() => { try { ClientOnPackageReceived(pack1); } catch (Exception e) { _logger.Error($"ClientOnPackageReceived error: {e}"); } }); } }, 0, _pollPackageQueueIntervalMs); }
public void Start(int timeToKeepCreatedRoomSec, int timeIntervalToCloseOpenRoomsWithoutUpdatesMs = 5000) { //start created rooms clear task var checkPeriodMs = 60000; // 10 time _clearTask = _taskScheduler.ScheduleOnInterval(() => { var cnt = 0; lock (_roomQueueSync) { while (_roomsQueue.TryPeek(out var room) && (DateTime.UtcNow - room.CreatedOn).TotalSeconds > timeToKeepCreatedRoomSec) { var roomId = _roomsQueue.Dequeue().Id; DeregisterRoom(roomId); cnt++; } } _logger.Info($"Cleaned {cnt} rooms"); }, 0, checkPeriodMs); if (timeIntervalToCloseOpenRoomsWithoutUpdatesMs > 0) { _closeTask = _taskScheduler.ScheduleOnInterval(() => { foreach (var room in _rooms) { if (room.Value.IsOpen() && (DateTime.UtcNow - room.Value.StateUpdatedOn).TotalMilliseconds > timeIntervalToCloseOpenRoomsWithoutUpdatesMs) { room.Value.UpdateState(RoomState.Closed); } } }, 0, 1000); } }
public void Listen() { //create reliable socket switch (Config.SocketType) { case SocketType.BareSocket: _reliableSocket = _socketFactory.GetReliableSockWithBareSocket(_logger); break; case SocketType.ThreadSocket: _reliableSocket = _socketFactory.GetReliableSockWithThreadSocket(_logger); break; default: throw new ArgumentOutOfRangeException(); } _reliableSocket.Listen(_port); _reliableSocket.AddEventCallbacks(OnReceivePacket, OnNewClientConnect, OnClientDisconnect); _lastTick = DateTime.UtcNow; _isTicking = false; _socketTickTask = TaskScheduler.ScheduleOnInterval(() => { if (_isStopping) { return; } lock (_isTickingMutex) { if (_isTicking) { return; } _isTicking = true; } var duration = (DateTime.UtcNow - _lastTick).Milliseconds; _lastTick = DateTime.UtcNow; if (duration > _maxSendDuration) // overlapping not matters { _maxSendDuration = duration; } try { _reliableSocket.Tick(); } catch { //empty } finally { lock (_isTickingMutex) _isTicking = false; } }, 0, Config.SocketTickTimeMs); //start protection _protectionManager.Start(); }
public void Start() { _getServerInfoTask = _taskScheduler.ScheduleOnInterval(async() => await GetList(), 0, _config.ServerInfoListUpdateIntervalMs); }
public void Start(int getBackendListIntervalMs = 1000) { _tickTask = _taskScheduler.ScheduleOnInterval(async() => await Load(), 2000, getBackendListIntervalMs); }
public void Start() { _pendingTask = _taskScheduler.ScheduleOnInterval(Tick, 0, _config.ConnectionCountCheckIntervalMs); _bannedPendingTask = _taskScheduler.ScheduleOnInterval(BannedTick, 0, _config.BanCheckIntervalMs); }
public void Start() { //schedule main task _mainTask = _taskScheduler.ScheduleOnInterval(async() => { _logger.Debug($"MmGroup tick"); if (_isGroupWorking) { return; } _isGroupWorking = true; try { lock (_queueSync) { var matchmakingPlayersCount = GetCurrentPlayersWeight(); var players = _playersManager.GetPlayers(Id, _totalPlayersNeeded - matchmakingPlayersCount, _maxMmWeight); foreach (var player in players) { _playersManager.SetOnMatchmaking(player.Id, true); AddPlayer(player); } matchmakingPlayersCount = GetCurrentPlayersWeight(); //if noone in collection - continue if (matchmakingPlayersCount == 0) { _isGroupWorking = false; return; } var oldestPlayer = GetOldestPlayer(); //try to add to existing room var room = _roomManager.GetRoom(Id, matchmakingPlayersCount, _matchmakingPlayers.Max(p => p.MmWeight), _matchmakingPlayers.Sum(p => p.MmWeight)); JoinRoomResult result = null; if (room != null) { //join to existing try { result = _roomManager.JoinRoom(room.Id, _matchmakingPlayers.ToDictionary(key => key.SessionId, value => value.Properties), _matchmakingPlayers.Max(p => p.MmWeight), _matchmakingPlayers.Sum(p => p.MmWeight)).Result; if (result.Result != RoomOperationResult.OK) { _logger.Error($"MM join room error (closing this room): {result.Result}"); room.UpdateState(RoomState.Closed); } } catch (Exception e) { // todo explore case _logger.Error($"MM join room error (closing this room): {e}"); room.UpdateState(RoomState.Closed); } } else if (EnoughWaiting(oldestPlayer) || IsEnoughPlayers()) { //players var playersDict = new Dictionary <Guid, Dictionary <byte, object> >(); foreach (var item in _matchmakingPlayers) { if (item != null && !playersDict.ContainsKey(item.SessionId)) { playersDict.TryAdd(item.SessionId, item.Properties); } } //add new room result = _roomManager.CreateRoom(Id, playersDict,//_matchmakingPlayers.ToDictionary(key => key.SessionId, value => value.Properties), RoomProperties).Result; } if (result != null) { ProcessJoinResult(result, oldestPlayer); } else { SendJoinInfoToCurrentMatchmakingGroup(); } } } catch (Exception ex) { _logger.Error($"MM tick error: {ex}"); } finally { _isGroupWorking = false; } }, 0, _matchMakingTickMs); }