如果我有一个Windows服务需要每30秒执行一次任务,这是更好使用; Timer()类或执行任务的循环会休眠几秒钟?Windows服务计划执行
class MessageReceiver
{
public MessageReceiver()
{
}
public void CommencePolling()
{
while (true)
{
try
{
this.ExecuteTask();
System.Threading.Thread.Sleep(30000);
}
catch (Exception)
{
// log the exception
}
}
}
public void ExecutedTask()
{
// do stuff
}
}
class MessageReceiver
{
public MessageReceiver()
{
}
public void CommencePolling()
{
var timer = new Timer()
{
AutoReset = true,
Interval = 30000,
Enabled = true
};
timer.Elapsed += Timer_Tick;
}
public void Timer_Tick(object sender, ElapsedEventArgs args)
{
try
{
// do stuff
}
catch (Exception)
{
// log the exception
}
}
}
windows服务将创建一个MessageReciever类的实例,并在新线程上执行CommencePolling方法。
看起来像http://stackoverflow.com/questions/1099516/for-a-windows-service - 这是一个更好的等待旋转或一个定时器,我发现通过搜索“服务计时器”。 – 2009-07-09 07:11:22