private async Task ProcessScheduledMessagesAsync() { logger.LogInformation("Starting to process scheduled messages queue"); using (IServiceScope scope = scopeFactory.CreateScope()) { IUnitOfWork unitOfWork = scope.ServiceProvider.GetRequiredService <IUnitOfWork>(); // TODO: there can be used parallel foreach IList <ScheduledMessageEvent> scheduledMessageEvents = await unitOfWork.ScheduledMessageEvents.GetAllPendingWithScheduledMessages(DateTime.UtcNow); foreach (ScheduledMessageEvent scheduledMessageEvent in scheduledMessageEvents) { try { ScheduledMessage scheduledMessage = scheduledMessageEvent.ScheduledMessage; string scheduledMessageId = scheduledMessage.Id.ToString(); logger.LogInformation("Processing scheduled message '{0}'", scheduledMessageId); await messageProcessor.SendMessageAsync(scheduledMessage, serviceCancellationToken); scheduledMessageEvent.State = ScheduledMessageEventState.Completed; AddPendingEvent(scheduledMessage); logger.LogInformation("Scheduled message '{0}' has been processed", scheduledMessageId); } // TODO: Added for debugging purposes, should be revisited. catch (ErrorResponseException exception) { string serializedBody = SafeJsonConvert.SerializeObject(exception.Body, new JsonSerializerSettings { Formatting = Formatting.Indented }); string message = $"Sending message was failed due Exception Message: '{exception.Message}', StackTrace: '{exception.StackTrace}', Body: '{serializedBody}'"; logger.LogError(message); } catch (Exception exception) { logger.LogError(exception, $"Sending message was failed due Exception {exception.Message}. StackTrace: {exception.StackTrace}."); } } await unitOfWork.SaveChangesAsync(serviceCancellationToken); } logger.LogInformation("Finished processing scheduled messages queue"); }