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 complet开发者_StackOverflow中文版ely different/more elegant approach?
maybe something like this:
class Reporter
{
int _HourLastRun;
public Reporter()
{
_HourLastRun = -1;
}
public void SendIfNeeded()
{
var currentHour = DateTime.Now.Hour;
if(currentHour != _HourLastRun)
{
_HourLastRun = currentHour;
SendReport();
}
}
}
Then simply instantiate this class where you create your timer and put the SendIfNeeded()
into the callback of the timer.
精彩评论