【发布时间】:2009-07-09 07:01:08
【问题描述】:
如果我有一个需要每 30 秒执行一次任务的 Windows 服务,这更好用; Timer() 类或执行任务然后休眠几秒钟的循环?
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 方法。
【问题讨论】:
-
看起来是stackoverflow.com/questions/1099516/…的副本,我通过搜索“服务计时器”找到的。
-
@John 谢谢。我尝试搜索“Windows 服务计时器”,但找不到任何东西。干杯
标签: c# windows-services