我正在开发windows服务,我想每分钟致电OnStart
。我原本有一个永远的while循环,但然后服务不会安装。如何每分钟调用一次方法,但要考虑该方法处理所花费的时间可能需要多次?
while (true)
{
Stopwatch stopWatch = new Stopwatch();
int totalTime = 0;
stopWatch.Start();
MethodToCall();
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
totalTime = ts.Seconds * 1000 + ts.Milliseconds;
if (totalTime < 60000)
{
Thread.Sleep(60000 - totalTime);
//ManualResetEvent.WaitOne(10000);
}
else
{
Thread.Sleep(30000);
}
}
所以,我怎样才能让我的方法每分钟的电话,但是当该方法已经超过1分钟,它将等待分钟数为n(比方说30秒),然后通过调用该方法重新开始。
你想要独立的线程吗? – Demodave
是否阻塞线程? – bastijn
那么你是说如果运行需要59秒,你希望它在下一秒重新启动,但是如果需要60秒运行,它应该等待30秒后才能重新启动? –