Search code examples
c#visual-studioazureservicebus

How can I get messages from Services Bus in a specific time?


I have this method that works great to get all the messages from my subscription in Azure Service Bus. But I want the messages that have been in there for the last 60 minutes. Is there a way to do that?

public void GetMessages()
{
    var connectionString = ConfigurationManager.ConnectionStrings["ServiceBus.EndPoint"].ConnectionString;
    var topic = ConfigurationManager.AppSettings["ServiceBus.Topic"];
    var subscription = ConfigurationManager.AppSettings["ServiceBus.Subscription"];
    var client = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription, ReceiveMode.PeekLock);

    client.RetryPolicy = new RetryExponential(TimeSpan.FromSeconds(0.1), TimeSpan.FromSeconds(5), 5);
    
    var messages = client.PeekBatch(100);

    foreach (var msg in messages)
    {
        string body = msg.GetBody<String>();
    }
}

Solution

  • I want the messages that have been in there for the last 60 minutes

    The short answer is "why?". You can peek at the messages, but when you'll try to get them, you're not promised to have the same messages. Or any messages at all.

    It's been said by many multiple times that a happy queue is an empty queue. If a message is sitting on a queue for 60 minutes, then something feels off. Almost as if a queue is used as a storage. Either your processors where all offline, and once they get online they should process regardless of how long the message was on the queue, or you're looking for some functionality that probably should be implemented via additional service/in a different way.