Search code examples
c#timer

C# Timer or Thread.Sleep


I am running a windows service and using a loop and Thread.Sleep to repeat a task, would it be better to use a timer method?

If yes a code example would be great

I am currently using this code to repeat

int curMinute;
int lastMinute = DateTime.Now.AddMinutes(-1).Minute;

while (condition)
{
   curMinute = DateTime.Now.Minute;

   if (lastMinute < curMinute) {
         // do your once-per-minute code here
         lastMinute = curMinute;
   }

   Thread.Sleep(50000);      // sleeps for 50 seconds

   if (error condition that would break you out of this) {
       break;      // leaves looping structure
   }
}

Solution

  • class Program
    {
        static void Main(string[] args)
        {
            Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000);
            Console.Read();
            timer.Dispose();
        }
    
        public static void TimeCallBack(object o)
        {
          curMinute = DateTime.Now.Minute;
          if (lastMinute < curMinute) {
           // do your once-per-minute code here
           lastMinute = curMinute;
        }
    }
    

    The code could resemble something like the one above