public ExampleService(ExampleWorker exampleWorker, ILogger <ExampleService> logger = null) //keeping exampleWorker concrete here for example simplicity... { _exampleWorker = exampleWorker; _logger = logger; }
private static async Task Receive(MessageQueue queue, bool limitHours, Tuple <int, int> hours, CancellationToken cancellationToken) { Log.Info("Starting Receive"); // Create our worker using (var worker = new ExampleWorker()) { // Loop until cancelled while (cancellationToken.IsCancellationRequested == false) { // Check if we are limiting run hours if (limitHours && hours != null) { var hour = DateTime.Now.Hour; if (hour >= hours.Item2 && hour < hours.Item1) { Log.Info("Hour limit reached"); break; } } Console.WriteLine(); // Read each queue message in a transaction so failures don't destory the message using (var transaction = new MessageQueueTransaction()) { Message message = null; try { transaction.Begin(); // Wait update to 1 minute for a message to appear in the queue message = queue.Receive(TimeSpan.FromMinutes(1), transaction); Log.Info($"{message.Id} {message.Label}: Received"); // Get the JSON body var body = await Read(message); // Some error handling if (body == null) { Log.Warn($"{message.Id} {message.Label}: Body could not be parsed"); transaction.Commit(); continue; } // Execute the message worker.Execute(message.Id, body, Log); Log.Info($"{message.Id} {message.Label}: Complete"); // Tell the queue we are done with the message so it is removed transaction.Commit(); } catch (TaskCanceledException) { Log.Warn($"{message?.Id} {message.Label}: TaskCanceledException"); // Tell the queue the message was not processed so it is returned transaction.Abort(); } catch (MessageQueueException e) { Log.Warn(e.Message); break; } catch (Exception e) { Log.Error($"{message?.Id} {message.Label}: {e.Message}", e); // Abort instead of commit if you want to leave it in the queue transaction.Commit(); } } } } }