I'm trying to create a windows phone application that records the accelerometer data at 100 Hz. I tried out both System.Windows.Threading.DispatcherTimer and System.Threading.Timer, but looking at the data recorded, neither were actually recording at 100 Hz. DispatcherTimer records 60-80 Hz, while Timer records at around 85-90 Hz. I don't think the problem is the phone not being able to handle it, since when I tried recording at 50 Hz, it was still lagging to only 40+ Hz. Here is a snippet of my code:
For DispatcherTimer:
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(10);
timer.Tick += new EventHandler(timer_Tick);
For Timer:
timer = new Timer(timer_Tick, null, 0, 10);
How do I make sure that I am recording at a fixed rate interval?
Windows Phone 7 - is not a real-time OS. None of the timer classes are exactly precise. All you're doing it saying that you want to wait at least this long. It takes some amount of time for everything to fire and you to end up notified that the timer has ticked once OS gets around to actually servicing the tick message.
Try to implement simple test: Print current time every 10 milliseconds, and you can see minimum error. When developers use 1 or 5 or 10 seconds like interval - this is not noticeable.
Related
I have something like the following:
myTimer.Interval = 100;
myTimer.Start();
...
In my myTimer_Elapsed(...) function something like the following:
DateTime.Now.TimeOfDay.ToString("g") written to a file.
Getting this as result:
System Time Now: 13:20:00,2959841
System Time Now: 13:20:00,3467621
System Time Now: 13:20:00,3789866
System Time Now: 13:20:00,4033991
System Time Now: 13:20:00,4356236
System Time Now: 13:20:00,4619891
I was expecting results bigger than 0,1 seconds because there are more process, and I was trying to calculate that impact, but I'm frustated because I don't know how can be even possible to have times lower than 0,1 seconds
Thanks in advance
What kind of timer do you use? If it's the Windows.Forms.Timer, it has a very limited accuracy .
The Windows Forms Timer component is single-threaded, and is limited
to an accuracy of 55 milliseconds. If you require a multithreaded
timer with greater accuracy, use the Timer class in the System.Timers
namespace.
Quoted from here: Windows.Forms.Timer
This question already has answers here:
Raise event in high resolution interval/timer
(3 answers)
Closed 9 years ago.
I have tried Dispatcher timer but it doesn't seem to be working correctly.
I have the tick event set up that adds to a tick counter every tick and it's just not doing the job right. I also have a Stopwatch to count how long it's been, and the numbers aren't matching up. Please let me know what kind of solution would work to give me 192 ticks each second.
Stopwatch sw = new Stopwatch();
public DispatcherTimer dt = new DispatcherTimer();
dt.Tick += dt_Tick;
dt.Interval = TimeSpan.FromMilliseconds(1000/192);
dt.Start();
sw.Start();
void dt_Tick(object sender, EventArgs e)
{
tick_textbox.Text = tick_counter.ToString();
seconds_textbox.Text = sw.Elapsed.ToString();
tick_counter++;
}
Now, I've lowered it to 8 per second, which should solve the resolution problem, but I'm getting wildly different outcomes from using an interval of TimeSpan.FromSeconds and TimeSpan.FromMilliseconds:
dt.Tick += dt_Tick;
dt.Interval = TimeSpan.FromSeconds(2 / 16);
dt.Start();
vs.
dt.Tick += dt_Tick;
dt.Interval = TimeSpan.FromMilliseconds(2000 / 16);
dt.Start();
What is the reason for that?
You're asking for an event every 5ms and the .NET timers are simply not reliable at this resolution
http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=815
From the article:
The conclusion I drew from all my testing is that, at best, you can count on a timer to tick within 15 milliseconds of its target time. It's rare for the timer to tick before its target time, and I never saw it be early by more than one millisecond. The worst case appears to be that the timer will tick within 30 milliseconds of the target time. Figure the worst case by taking your desired target frequency (i.e. once every 100 milliseconds), rounding up to the next multiple of 15, and then adding 15. So, absent very heavy CPU load that prevents normal processing, a 100 ms timer will tick once every 99 to 120 ms.
You definitely can't get better resolution than 15 milliseconds using these timers. If you want something to happen more frequently than that, you have to find a different notification mechanism. No .NET timer object will do it.
There are ways to get this resolution but they typically involve specific hardware designed for high-frequency timing applications and driver interop for their events. I've done this before using an acousto-optic modulator, laser source and CCD.
Scenario:
In a Winform application(C#), I have a Datagridview in which I have to display 4 countdown timers in the format "mm:ss".
Time Interval must be 1000ms.
I was counting the timer down in the elapsed event of system.timers.timer.
On all 4 timers I'm starting to countdown from 2 mins (02:00).
Issue:
It takes more time(125 seconds) than 2 mins, to reach 00:00.
Similarly for 4 mins it takes 7-10 more(247 -250) seconds to reach 00:00
Timers on systems are somewhat of an inaccurate beast. Better systems generally provide better timers but even the best system has slippage.
You also need to remember that your process isn't going to be in "full control" 100% of the time, it will at times be pushed into the background and have to share the processor with other applications so whilst it's does its best to keep track of the time.
What you probably want is a High Precision Timer (aka stopwatch) in C#. Have a look at This thread and This article on selecting timer mechanisms for some more information.
If you need time resolution of that type (i.e. actual clock or countdown clock), you should use the real-time clock.
You still use a timer with sub-second resolution to fire frequently enough for display purpose, but you don't add up those times, you use the real-time clock to get the real elapsed time (DateTime.Now - startTime).
First off you should run this little test and see the drift in near real-time. I lose a 1 second after 72 timer elapsed events (this is with very little actual work).
using (var timer = new Timer(1000))
{
var start = DateTime.Now;
var i = 0;
timer.Elapsed += (sender, args) => Console.WriteLine("{0} -> {1}", ++i, (DateTime.Now - start).TotalMilliseconds);
timer.Start();
Thread.Sleep(130*1000);
}
I'm not sure how precise your app needs to be but you can get "good enough" by using the delta between the start time & now and subtracting that from your initial value and killing the timer at zero. You will lose seconds with this approach and there's a reasonable chance that lost second could happen # 0:00 causing a -0:01 tick, which you will need to handle.
var countdownSeconds = 120;
var startedAt = DateTime.Now;
var timer = new Timer(1000);
timer.Elapsed += (sender, args) => Display(countdownSeconds - (int)((DateTime.Now - startedAt).TotalSeconds));
timer.Start();
//- be sure to dispose the timer
I have a dll consumed by a service. Its basic job is to run every X minutes and perform some system checks.
In my dll I have a top level class that declares a System.threading.timer and a Timercallback.
The constructor for the class initialises the timerCallback with my thread function.
In my "Onstart" handler I initialise the timer with the timercallback and set the next time to fire and interval time. In my case its every 10 minutes.
Usually in these 10 minute checks there is nothing to do but the service is forced to do something at least once every day at a set time.
My problem: I am finding that during testing, the time the daily check is carried out every day is slowly drifitng away from the desired start time of 8.30. e.g. over about 20 odd days my time has drifted from 08.30 to 08.31.35. It drifts about 4 - 6 seconds every day.
My question: does anyone know why the time is drifting like this and how can I make it stick to its allotted time?
thanks
The time "drifts" because the timer is simply not that precise. If you need to run your code as closely as possible to a certain interval, you can do something like this:
public void MyTimerCallback(object something) {
var now = DateTime.UtcNow;
var shouldProbablyHaveRun = new DateTime(
now.Year, now.Month, now.Day,
now.Hour, now.Minute - (now.Minute % 10), 0);
var nextRun = shouldProbablyHaveRun.AddMinutes(10.0);
// Do stuff here!
var diff = nextRun - DateTime.UtcNow;
timer.Change(diff, new TimeSpan(-1));
}
...assuming you are using a System.Threading.Timer instance. Modify the example if you are using any other type of timer (there are several!).
Why not check every minute if the action needs to be performed?
ie:
if (DateTime.Now.Minute % 10) == 0
it takes a finite amount of time to do the operations you are doing in your timer method handler, so it makes sense that it's not going to happen every 10 minutes to the second, especially if you are scheduling the next wakeup after doing your checks and such. if you are already checking anyway for answering is it time to do this, you should make your timer fire more frequently to satisfy the resolution you need and trust your check of when it should execute something to make sure that it does. you probably need some sort of persistence to make sure it doesn't execute twice (if that is important) in case there is a shut down/restart and the state of knowing whether it has already run is not still in memory.
Here is my take:
while ((DateTime.Now - lastRunTime).TotalSeconds < 600)
CurrentThread.Sleep(1000);
or just register a windows timer and execute in response to the event/callback
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 600 seconds.
aTimer.Interval=600000;
aTimer.Enabled=true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("10 minutes passed!");
}
Timers aren't exact, just approximate. Don't use the logic of "just add 10 minutes". Each time your timer fires, you need to check for time skew and adjust.
eg. If you say "wake me up in 10min", and it wakes you up in 10min 1sec, then the next timer needs to be 9min 59sec, not 10min.
Also, you want to assign your next timer at the end of your logic.
eg. say you want to start taskA every 10min and it takes 2 seconds to run. Your timer starts and 10 minutes later it wakes up to run taskA. It kicks off, finishes, now you add 10 minutes. But it took 2 seconds to run your task. So 10 minutes from the time your code ran will be skewed by 2 seconds.
What you need to do is predict the next time you need to run and find the difference between now and then and set the timer to that difference.
I made a student check_list program that's using Bluetooth adapter searches students cell phones Bluetooth and checks that are they present or not and saves students information with date in table on data base.all them works great.But I want to make it automatic that I will put my program on some computer like works as an server and program will make search every lessons start time like 08.30 , 10.25 ...
My question is how to use timer? I know how to use timer but How can I use it on every lessons start time?I have table that includes start time of lessons. Also am I have to stop timer after search ends?And If I stop timer could I re-run timer again?
And one additional question that how can I track that new students come or some body left class room?
http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
You could periodically check the current time (like every 30 seconds with a simple timer) and if nothing happens, you sleep, if it's 10.25: start your bluetooth polling.
During class times you could just poll every 5 minutes to see if new students are there.
You could set the timer's Interval property to be the difference between the current time and the time for the next lesson; then reset the difference after that lesson is finished to be ready for the next. However, this has obvious pitfalls. What happens when you start/stop the timer? You will need to reset the Interval for the next lesson.
Or, you could make a timer which checks periodically if it is time to recheck the bluetooth devices and if it is time does so. It probably wouldn't need to be too accurate.
// Add your own DateTimes
DateTime[] times = new[] { new DateTime(2010, 4, 20, 16, 30,0,0), new DateTime(2010, 4, 20, 17, 0,0,0) };
Timer t = new Timer();
t.Interval = 30000; // 30 seconds, feel free to change
// Each 30 secs check to see if the _time_ is before one of the ones specified; if it is RunMethod()
t.Tick += (sender, e) => { if (times.Any(d => { DateTime dt = DateTime.Now; new DateTime(dt.Year, dt.Month, dt.Day, d.Hour, d.Minute, d.Second, d.Millisecond).CompareTo(dt) <= 0 })) RunMethod(); }
I'd use Quartz.NET and schedule the jobs instead of messing with the timer...