.NET timer imprecise?
I am developing an application and I need to get the current date from the server (it is different from the machine date). I am getting the date from the server and with a simple Split I create a new DateTime:
globalVars.fec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(infoHour[0]), int.Parse(infoHour[1]), int.Parse(infoHour[2]));
globalVars is a class and fec is a public static variable, so I can access it anywhere in the application (bad coding I know ...). Now I need to set a timer if this date is equal to some of the dates I have stored in the list, and if it is, I just call the function.
List<DateTime> fechas = new List<DateTime>();
Before getting the date from the server, I was using the computer's date, so to check if the dates match, I used this:
private void timerDatesMatch_Tick(object sender, EventArgs e)
{
DateTime tick = DateTime.Now;
foreach (DateTime dt in fechas)
{
if (dt == tick)
{
//blahblah
}
}
}
Now I have a date from the server, so DateTime.Now cannot be used here. Instead, I created a new timer with Interval = 1000 and per tick. I am adding 1 second to globalVars.fec using:
globalVars.fec = globalVars.fec.AddSeconds(1);
But the watch is not accurate, and every 30 minutes the watch loses about 30 seconds.
Is there any other way to do what I am trying to do? I thought about using threading.timer, but I need to be able to access other threads and non-static functions.
a source to share
If you create an atimer at 1000ms interval, it will be called no earlier than 1000ms. This way, you can pretty much guarantee that it will be called for more than 1000ms, which means that you will be wasting time by adding 1 sec to that timer. This will accumulate error on every tick. The best approach is to record the start time and use the current time to determine the current offset from that known start time, so you don't accumulate any error in your time. (There will still be some error, but you won't get out of touch in real time over time)
Different timers (Forms.Timer, Thread.Timer, etc.) will also have different precision - Forms.Timer is especially bad for precision.
You can also use high performance time to track time better - see here .
a source to share