Search code examples
c#timerwait

How to pause C# code for ten minutes at the start of each hour


I'm trying to get my application to pause for nine to ten minutes at the start of each hour.

I've been able to get my application to pause for that amount of time

Random waitTime = new Random();
int milliseconds = waitTime.Next(3000, 5000);
System.Threading.Thread.Sleep(milliseconds);

I shortened the time in my code for testing purposes.

Now I need to tie that into something that checks if the current time is in between (4:00, 4:10) or (5:00, 5:10) or (21:00, 1:00) and resume if it is not.


Solution

  • You wish to continue with your current pattern of using Thread.Sleep(n), can use a simple loop.

    while (DateTime.Now.Minute <=10)
    {
        Thread.Sleep(1000);
    }
    

    In general though it would be better to schedule the task or at least to use async instead of blocking the thread.