基本的にx秒ごとに起動し、メール通知を送信する必要があるかどうかを確認してからスリープ状態に戻るC#のWindows NTサービスがあります。
次のようになります (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 ミリ秒後に別のエントリが記録されるのはなぜですか??
ここは、完全に調子が悪いようです....
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 クラスがあります。:-)