我需要定期在窗口服务中调用一个函数。 c#vs 2008 应该从配置文件中设置间隔 哪种方式最好?请建议
while (Service1.serviceStarted)
{
CheckFile();
Thread.Sleep(60000);
}
Thread.CurrentThread.Abort();
或
private Timer timer;
private void InitializeTimer()
{
if (timer == null)
{
timer = new Timer();
timer.AutoReset = true;
timer.Interval = 60000 * Convert.ToDouble(
ConfigurationSettings.AppSettings["IntervalMinutes"]);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
}
}
<add key="IntervalMinutes" value="5" />
private void timer_Elapsed(object source,System.Timers.ElapsedEventArgs e)
{
RunCommands();
}
谢谢
KJ
答案 0 :(得分:0)
我会使用计时器。 Thread.Sleep将导致该线程在指定的时间段内处于非活动状态。我知道你说这是针对服务器的,但如果它与gui有任何关系可能非常糟糕!
BTW我相信你可以在这里阅读更多...... Stackoverflow Q&A
答案 1 :(得分:0)
http://quartznet.sourceforge.net/尝试使用Quartz.net这是一个很好的事情,可以安排Job Job,并提供很多可以帮助你的Job触发器。
答案 2 :(得分:0)
您可以使用this library访问内置Windows任务计划程序并将任务添加到内置Windows任务计划程序。这也允许更复杂的调度。
答案 3 :(得分:0)
使用计时器。
使用Thread.Sleep()的代码更紧凑,但它可能会导致您的服务无法响应来自服务控制管理器的请求(并且在用户试图阻止它时似乎挂起)。