65.9K
CodeProject is changing. Read more.
Home

Using DateTime and TimeSpan objects to test for a specific time interval.

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 16, 2011

CPOL
viewsIcon

8820

A simple way to determine when to execute something based on the local systems time using .NET DateTime and TimeSpan objects.

bool work = true;
//execute at 2:06 PM
TimeSpan timeToExecute = new TimeSpan(14,6,00);
do
{
  DateTime nowTime = DateTime.Now;
  TimeSpan systemTime = new TimeSpan(nowTime.TimeOfDay.Hours,
                                       nowTime.TimeOfDay.Minutes,
                                       nowTime.TimeOfDay.Seconds);
  Console.WriteLine(systemTime);
  Console.WriteLine(timeToStop);
 
  if(timeToExecute.CompareTo(systemTime) == 0)
  {
    //Execute whatever you need to here.
    Console.WriteLine("END");
  }
}while(work);