Close

Timer trigger to read messages from a queue

When you want to develop an Azure Function to process messages from a queue, the first hunch is to use a queue trigger. But, let’s say you want to processes messages from a queue every minute. In that case you need a timer trigger. In the example below you see an example of an Azure Function with a timer trigger, an import of multiple libraries and a call of a Logic App using an URI from AppSettings. I need to check if I found a message (message!=null). On the other hand, if there are multiple messages on the queue, they will be processed one-by-one.
#r “Microsoft.WindowsAzure.Storage” #r “Newtonsoft.Json” using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Queue; using System.Text; using System.Net.Http; using Newtonsoft.Json; private static string logicAppUri = Environment.GetEnvironmentVariable(“ProcessOpdrachtenURI”); public static async Task Run(TimerInfo myTimer, TraceWriter log) { log.Info($”Function TriggerTimedProcessOpdrachten started”); // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable(“ahakstorage_STORAGE”)); // Create the queue client. CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); // Retrieve a reference to a queue. CloudQueue opdrachtQueue = queueClient.GetQueueReference(“opdrachtevents”); // GetMessage CloudQueueMessage message = await opdrachtQueue.GetMessageAsync(); if (message != null) { log.Info($”{message.AsString}”); using (var client = new HttpClient()) { var response = client.PostAsync(logicAppUri, new StringContent(message.AsString, Encoding.UTF8, “application/json”)).Result; } opdrachtQueue.DeleteMessage(message); } log.Info($”Function TriggerTimedProcessOpdrachten ended”); }
Note: In the end I didn’t need the Newtonsoft.Json library, but I left that library in for learning purposes.