Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this code loop infinitely?

Tags:

c#

timer

I have the following code, does this run an endless loop?
I am trying to schedule something every minute and the console application should run continuously until I close it.

class Program
{
  static int curMin;
  static int lastMinute = DateTime.Now.AddMinutes(-1).Minutes;

 static void Main(string[] args)
 {
   // Not sure about this line if it will run continuously every minute??
   System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimCallBack), null, 1000, 60000);

  Console.Read();
  timer.Dispose();
 }
   private static void TimCallBack(object o)
   {
      curMin = DateTime.Now.Minute;
      if (lastMinute < curMin)
      {
          // Do my work every minute
          lastMinute = curMin;
      }
    }

}
like image 455
Picflight Avatar asked Dec 09 '22 17:12

Picflight


2 Answers

KISS - or are you competing for the Rube Goldberg award? ;-)

static void Main(string[] args)
{
   while(true)
   {
     DoSomething();
     if(Console.KeyAvailable)
     {
        break;     
     }
     System.Threading.Thread.Sleep(60000);
   }
}
like image 126
Sky Sanders Avatar answered Dec 23 '22 13:12

Sky Sanders


I think your method should work assuming you don't press any keys on the console window. The answer above will definitely work but isn't the prettiest.

like image 38
beyerss Avatar answered Dec 23 '22 12:12

beyerss