My problem is I'm writing an app that controls external hardware using a state machine. I'm replacing code written over 10 years ago in a much earlier version of VB.
Certain things have to happen at certain times, so after a bit of research I used the system.timers.timer class to increment a millisecond counter and fired actions as the counter incremented past the due time. As I needed sub 1 second accuracy I used a 100ms interval for that timer.
The system ran terribly slow, by about 3 sec each minute. Another poster on this forum noticed this a month ago with the system.windows.forms timer and was directed to other "more accurate" timers. I already recognised that and thought a few milliseconds error in the system.timers.timer would be OK. What I didn't realise was that the error is PER TICK so it accumulates very fast.
To see this in practice, create a form with a button and two checkboxes and add this code
Public Class frmTimerTest Private MyTimer As System.Timers.Timer Private MyTime As Integer Private TimeNow As Date Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'set up the timer and clock MyTimer = New System.Timers.Timer() AddHandler MyTimer.Elapsed, AddressOf MyTimerTick MyTimer.Interval = 100 'play with this to see accuracy goes up as interval goes up MyTimer.AutoReset = True MyTimer.SynchronizingObject = Me TimeNow = TimeOfDay() MyTimer.Start() End Sub Private Sub MyTimerTick(ByVal sender As Object, ByVal e As EventArgs) MyTime += MyTimer.Interval TextBox1.Text = CInt(MyTime / 1000) TextBox2.Text = (TimeOfDay() - TimeNow).TotalSeconds End Sub End Class
Run the form, click the button (while watching a real clock if you like) and watch the numbers in the two textboxes go out of sync. From the earlier poster I guess the timer always runs slow. I estimate there is an average error of about +7ms per tick.
So I've modified my app so instead of waiting for the incremented time to reach the next event, it sets the timer interval directly to the next event time. That way I get just a few ms error each event, but over a number of starts it still ends up a second slow, which may not seem much but will undoubtedly lead to complaints.
My next option is to use the timer just as a way of generating ticks and in the tick handler use the system clock to determine the true time. Only issue there is everything has to be in increments of 1 sec which isn't ideal, some events are separated by 0.5 or 1.5 sec.
I could use the "multimedia timer" but getting it into VB.NET doesn't look easy, and I've seen suggestions it isn't available in Win7. Annoyingly, the old VB app used a built-in "timer" function which free ran through the app and apparently provided absolute accuracy.
What do other people do?