Search code examples
c#datetimewaitdayofweekandand

Escaping while loop, while conditions are false


I'm seeing this not wait during specified times.

I've been trying to learn c# and don't know exactly what all the syntax is yet. I just want to know if there are better ways of accomplishing this task.

while (DateTime.Now.DayOfWeek == DayOfWeek.Saturday 
    && DateTime.Now.DayOfWeek == DayOfWeek.Sunday 
    && DateTime.Now.Hour <=8 
    && DateTime.Now.Hour >=18  
    && DateTime.Now.Minute <=9)
{
    Random waitTime = new Random();
    int milliseconds = waitTime.Next(120000, 180000);
    System.Threading.Thread.Sleep(milliseconds);
}

I want it to wait while it is saturday, or sunday, if it before 0800, after 1800, or if it is in the first ten minutes of each hour.

The problem is, I've seen it exit the loop at 7:05pm on a monday, which is two conditions. Am I using the && function correctly, or should I replace it with something else?


Solution

  • JonH is right it cannot be both Saturday and Sunday. Here's what your code should look like

                Random myRand = new Random();
            bool isSatOrSun = DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday;
            bool isNotBetween8And1800 = DateTime.Now.Hour <= 8 || DateTime.Now.Hour >= 18;
            bool isFirstTenMinutes = DateTime.Now.Minute <= 9;
    
            //if you want to do Between 8 & 18 on Saturday/Sundays OR first 10 minutes of each hour on Saturday/Sunday
    
            while(isSatOrSun && (isNotBetween8And1800 || isFirstTenMinutes))
            {
                //do your sleep
                int waitTime = myRand.Next(120000, 180000);
                System.Threading.Thread.Sleep(waitTime);
    
                //now recheck your variables
                isSatOrSun = DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday;
                isNotBetween8And1800 = DateTime.Now.Hour <= 8 || DateTime.Now.Hour >= 18;
                isFirstTenMinutes = DateTime.Now.Minute <= 9;
            }
    
    
            //if you want to do all day on Saturday/Sundays OR Between 8 & 18 any day of the week OR  first 10 minutes of each hour any day of the week
    
            while (isSatOrSun || isNotBetween8And1800 || isFirstTenMinutes)
            {
                //do your sleep
                int waitTime = myRand.Next(120000, 180000);
                System.Threading.Thread.Sleep(waitTime);
    
                //now recheck your variables
                isSatOrSun = DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday;
                isNotBetween8And1800 = DateTime.Now.Hour <= 8 || DateTime.Now.Hour >= 18;
                isFirstTenMinutes = DateTime.Now.Minute <= 9;
            }