Sleep in loop when application is running, but sleeps too few
-
28-09-2019 - |
Pergunta
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.
Solução
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.
Outras dicas
The argument of the Sleep method is in milliseconds, so if you want to sleep for 10 minutes:
Thread.Sleep(10 * 60 * 1000);
3600 is 3.6 seconds. If you want it to sleep for 10 minutes, you should set it to 600000.
Thread.Sleep(1000 * 60 * 10); // Milliseconds(1000) * Seconds(60) * Minutes(10)
Which is equal to:
Thread.Sleep(600000);
thrad.sleep is in milli seconds 10 mins would be thread.sleep(1000 * 60 * 10)
Why are you using thread.sleep, you may be better using a timer
10 minutes in milliseconds is 600,000. Your Sleep will only wait 3.6 seconds. It's often clearer to use a timespan:
Thread.Sleep(new TimeSpan(0,10,0));
thx, my big mistake. John Feminella i use thread now.
private static void Main(string[] args)
{
Thread thrd1 = new Thread(new ThreadStart(Trmain));
thrd1.Start();
}
private static void Trmain()
{
for (; ; )
{
Console.WriteLine("waiting 10 minutes...");
Thread.Sleep(1000 * 60 * 10);
}
}
thx all