我有一个c中的windows nt服务,它基本上每x秒唤醒一次,检查是否需要发送任何邮件通知,然后返回休眠状态。
看起来像这样
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个计时器类-为什么??)