protected override async Task ExecuteAsync(CancellationToken stoppingToken) { Init(); var marketUpdate = new Timer(MarketUpdate, null, 0, 1000); var priceUpdate = new Timer(PriceUpdate, null, 0, 1000); var newsUpdate = new Timer(NewsUpdate, null, 0, 1000 * 60 * 60); while (!stoppingToken.IsCancellationRequested) { if (_realTimeStockService.IsMarketOpen()) { marketStatus = "Open"; try { if (!_websocketService.IsConnecting() && !_websocketService.IsOpen()) { _websocketService.Connect(stoppingToken); } if (_websocketService.IsConnecting()) { _logger.LogDebug($"Connecting to websocket..."); } if (_websocketService.IsOpen()) { _realTimeStockService.Ready = true; _logger.LogDebug("Websocket connected"); SubscribeStocks(true); var buffer = new ArraySegment <byte>(new byte[2096]); while (_realTimeStockService.IsMarketOpen()) { UpdateWithWebsocket(await _websocketService.Receive(buffer, stoppingToken)); } await SubscribeStocks(false); await _websocketService.Disconnect("Market Closed", stoppingToken); _logger.LogDebug("Websocket disconnected"); marketStatus = "Closing"; _logger.LogDebug("Waiting for market close prices"); var lastUpdateDate = UpdateWithDatabaseEnd(); while ((lastUpdateDate.Hour * 100 + lastUpdateDate.Minute) < _realTimeStockService.marketCloseTime) { await Task.Delay(5_000); lastUpdateDate = UpdateWithDatabaseEnd(); } _realTimeStockService.Send(); } } catch (Exception ex) { _logger.LogError($"ERROR - {ex.Message}"); } await Task.Delay(10_000); } else { marketStatus = "Closed"; var leftToOpening = _realTimeStockService.GetTimeToOpenMarket(); _logger.LogDebug("Market opening in: " + leftToOpening.ToString()); await Task.Delay(leftToOpening); marketStatus = "Opening"; _logger.LogDebug("Waiting for market open prices"); var lastUpdateDate = UpdateWithDatabaseOpen(); while ((lastUpdateDate.Hour * 100 + lastUpdateDate.Minute) < _realTimeStockService.marketOpenTime) { await Task.Delay(5_000); lastUpdateDate = UpdateWithDatabaseOpen(); } PullHistoricalPrices(); PullSplits(); _realTimeStockService.Ready = true; } } }
async public Task <ActionResult> Disconnect() { await _websocketService.Disconnect("Closure requested from controller", new CancellationToken()); return(Ok(String.Format("{0}\n{1}", _websocketService.WebSocket.CloseStatus.ToString(), _websocketService.WebSocket.CloseStatusDescription))); }