Search code examples
c#delay

C# How can I add a 5 second delay after I instantiate an API call once its done?


I have a loop where I pass in phone numbers to send text messages using a 3rd party call to their service. When it sends to the 3rd party, it comes back right away to a separate data page URL that consumes the status code of (sent, not sent). This is so we know if the text made it. But it happens so quickly that the page isn't able to handle all of the requests so fast. So I wanted to add a small 3-5 second delay once the text is sent, then it continues to loop through...sends again, pauses for 5 seconds, then loops around and sends the next one. Basically spreading out the sends with 5 seconds in between.

I have seen different timer or delay requests but I dont know which one is best for this situation.

Code flow

LOOP 1. Send Text 2. Wait 5 seconds 3. Loop back

END LOOP


Solution

  • You can just call Thread.Sleep() and pass in the number of milliseconds (or a TimeSpan) that you want to sleep after each call to send the text.

    To use this method, you will need to add using System.Threading; to your usings.

    // Assuming you're looping over some collection of phone numbers...
    foreach (var phoneNumber in phoneNumbers)
    {
        SendSMS(phoneNumber, message);  // <-- Your code to send a text here
        Thread.Sleep(TimeSpan.FromSeconds(5));
    }