Search code examples
c#datetimetimervisual-studio-2019

How to set timer based on 2 period of hours?


I have a single function that needs to run on 2 separate time period. 8AM-12AM Period1, 12AM-8AM Period2.

I have 1 Timer at the moment that runs 24/7 for every 1 hour.

How do i split this timer into 2 separate time period?

I have a pre-written code but i believe this is not an efficient method so i would like to ask community if there's a more efficient way to do this.

Below is my code example

if (DateTime.Now.Hour == 8 && DateTime.Now.Minute == 0)
{
    LogMessageToFile("Running Peak Period - Period 1");
    LogMessageToFile("Check will now do every 1 count");
    //Code here
    --SomeCodes--
}
else if (DateTime.Now.Hour == 0 && DateTime.Now.Minute == 0)
{
    LogMessageToFile("Running Night Period - Period 2");
    LogMessageToFile("Check will now do every 3 count");
    //Code here
    --SomeCodes--
}

I see that my code then will only run once when it reach 8am and 12am. Result should be that it runs the entire period.

I.e. 8 am until 12 midnight, then 12 midnight until 8 am.


Solution

  • I'd suggest to try 'more-less' comparison instead of equal-comparison. Eg.

    if (DateTime.Now.Hour >= 8 && DateTime.Now.Hour <= 12) // this means condition that current time is between 8 and 12 hours
    {
      //Period #1
    }
    else
    {
      //Period #2
    }
    
    

    upd: misread your question. If you would like the code to be executed between 8 AM and 12 PM then you should make a condition based on a 24h time format, eg:

    if (DateTime.Now.Hour > 0 && DateTime.Now.Hour <= 8)
    {
      //Night time
    }
    else
    {
      //Peak time
    }