Search code examples
c#sleepthread-sleep

Sleep in loop when application is running, but sleeps too few


private static void Main(string[] args)
{
    for (;;)
    {
        TemporaryCityTool.TemporaryCityTool.AddCity();
        Console.WriteLine("waiting...");
        Thread.Sleep(3600);
    }
}

why Thread.sleep not working. I am getting message waiting all the time. I want that application will wait 10 minutes then continue again.


Solution

  • Thread.Sleep takes a value in milliseconds, not seconds, so this only tells the current thread to wait 3.6 seconds. If you want to wait 10 minutes, use:

    Thread.Sleep(1000 * 60 * 10);  // 600,000 ms = 600 sec = 10 min
    

    This is probably an inappropriate use of Sleep, though. Consider using a Timer instead, so that you get something along the lines of:

    // Fire SomeAction() every 10 minutes.
    Timer timer = new Timer(o => SomeAction(), null, 10 * 60 * 1000, -1);
    

    See this StackOverflow thread for more details on that.