I have a timer that runs every second, the code is bellow:
public MainWindow()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += new EventHandler(someEventHandler);
timer.Start();
}
private void someEventHandler(Object sender, EventArgs args)
{
TVMonitor TVMonitor = new TVMonitor();
if (TVMonitor.NeedsTurningOn())
{
Console.WriteLine("on");
TVCOM.SendCommand(SettingManager.GetTVCode("on") + Environment.NewLine);
}
}
In the function NeedsTurningOn() I have the following:
public bool NeedsTurningOn()
{
var turnon = (from settings in context.SystemSettings
where settings.SystemSettingName == "TVOnTime"
select settings).First();
if (turnon.SystemSettingValue == String.Empty)
{
return false;
}
DateTime date = Convert.ToDateTime(turnon.SystemSettingValue);
Console.WriteLine("Turnontime: " + date);
Console.WriteLine("currenttim: " + DateTime.Now);
if (date != DateTime.Now)
{
Console.WriteLine("false");
return false;
}
else
{
Console.WriteLine("true");
return true;
}
}
Now in the console which I am using for debugging, I have the following output:
...
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:07
false
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:08
false
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:09
false
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:10
false
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:11
false
Turnontime: 11/04/2011 14:05:10
currenttim: 11/04/2011 14:05:12
false
...
Why is this still firing off a false instead of true once the date is the same?
You only compare the times every second – the milliseconds will still be different (especially assuming the turn-on time you compare to most likely doesn’t use milliseconds). To compare in a second resolution you could do something like this: