从定时器内调度任务/方法
我想在 Windows 服务中每小时一次转换一个方法。我想使用一个轮询计时器,而不是添加“Windows 任务”。
在计时器回调中,我通过以下代码检查是否调用该方法,其中_config.PollingInterval是计时器的时间间隔。
if (DateTime.Now.Subtract(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0)) < TimeSpan.FromMilliseconds(_config.PollingInterval)) {
SendReport();
}
由于某种原因,该条件在同一分钟内满足两次(例如 08:00)。我猜想某个地方存在逻辑错误,因为可以保证只有一个计时器。
对于可行的甚至完全不同/更优雅的方法有什么提示吗?
From within a Windows service I would like to cast a method once an hour. A polling timer exists which I would like to use rather than adding a "Windows Task".
In the timer callback, I am checking whether to call the method or not by the following code, where _config.PollingInterval is the interval of the timer.
if (DateTime.Now.Subtract(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, 0, 0)) < TimeSpan.FromMilliseconds(_config.PollingInterval)) {
SendReport();
}
For some reason, the condition is met twice within the same minute (e.g. 08:00). I guess there is a logical error somewhere, since it's assured that there is only one timer.
Any hints for a working or even completely different/more elegant approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许是这样的:
然后只需在创建计时器的地方实例化此类,并将
SendIfNeeded()
放入计时器的回调中。maybe something like this:
Then simply instantiate this class where you create your timer and put the
SendIfNeeded()
into the callback of the timer.