我在C#中有一個Windows NT服務,它基本上每隔x秒就會喚醒一次,檢查是否需要發送任何郵件通知,然後再回到睡眠狀態。Windows服務中的計時器 - 不是真的有用嗎?
它看起來像這樣(的Timer
類是從System.Threading
命名空間):
public partial class MyService : ServiceBase
{
private Timer _timer;
private int _timeIntervalBetweenRuns = 10000;
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// when NT Service starts - create timer to wake up every 10 seconds
_timer = new Timer(OnTimer, null, _timeIntervalBetweenRuns, Timeout.Infinite);
}
protected override void OnStop()
{
// on stop - stop timer by freeing it
_timer = null;
}
private void OnTimer(object state)
{
// when the timer fires, e.g. when 10 seconds are over
// stop the timer from firing again by freeing it
_timer = null;
// check for mail and sent out notifications, if required - works just fine
MailHandler handler = new MailHandler();
handler.CheckAndSendMail();
// once done, re-enable the timer by creating it from scratch
_timer = new Timer(OnTimer, null, _timeIntervalBetweenRuns, _timeIntervalBetweenRuns);
}
}
發送郵件和所有工作得很好,服務也喚醒每10秒(在現實中,這是一個來自配置文件的設置 - 這個例子簡化了)。
然而,有時,該服務似乎太快醒來....
2010-04-09 22:50:16.390
2010-04-09 22:50:26.460
2010-04-09 22:50:36.483
2010-04-09 22:50:46.500
2010-04-09 22:50:46.537 ** why again after just 37 milliseconds...... ??
2010-04-09 22:50:56.507
工作正常,以22:50:45.500 - 爲什麼它只有37毫秒後登錄另一個項目?
這裏,現在看來,這是完全不正常的....好像醒了兩次,甚至每拍攝10秒的三倍以上....
2010-04-09 22:51:16.527
2010-04-09 22:51:26.537
2010-04-09 22:51:26.537
2010-04-09 22:51:36.543
2010-04-09 22:51:36.543
2010-04-09 22:51:46.553
2010-04-09 22:51:46.553
2010-04-09 22:51:56.577
2010-04-09 22:51:56.577
2010-04-09 22:52:06.590
2010-04-09 22:52:06.590
2010-04-09 22:52:06.600
2010-04-09 22:52:06.600
任何想法,爲什麼?這不是一個大問題,但我擔心它可能會開始給服務器帶來太多的負載,如果我配置的時間間隔(10秒,30秒 - 無論什麼)似乎越來越被忽略,服務運行的時間越長。
我在服務代碼中遺漏了一些非常基本的東西嗎?我結束了多個定時器,或者什麼?我似乎無法真正弄清楚.....我有沒有選錯計時器(System.Threading.Timer
)? .NET中至少有3個Timer類 - 爲什麼? :-)