Winforms timer not accurate - vb.net

I have an app that uses a System.Windows.Forms.Timer and am seeing issues with the timer interval. When I use an interval of 1000 for a duration of 180 seconds the elapsed time is consistently around 183 seconds. When I use an interval of 995, the elapsed time is accurate (i.e. 180 seconds). I have tried this on 3 different PCs with the same results on each. The code below uses 2 textboxes to display the start and end times and a label as a countdown timer.
Can anyone explain this behavior?
Public Class Form1
Private WithEvents tmr As New System.Windows.Forms.Timer
Private Duration As Integer = 180
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RunTimer()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblActivityTimer.Text = FormatCounter(Duration)
tmr.Interval = 1000
End Sub
Private Sub RunTimer()
tmr.Start()
TextBox1.Text = Now.ToString()
End Sub
Private Function FormatCounter(sec As Integer) As String
Dim Hours, Minutes, Seconds As Integer
Hours = sec \ 3600
Seconds = sec Mod 3600
Minutes = Seconds \ 60
Seconds = sec Mod 60
FormatCounter = Hours.ToString.PadLeft(2, "0"c) & ":" _
& Minutes.ToString.PadLeft(2, "0"c) _
& ":" _
& Seconds.ToString.PadLeft(2, "0"c)
End Function
Private Sub tmr_Tick(sender As Object, e As EventArgs) Handles tmr.Tick
Duration -= 1
lblActivityTimer.Text = FormatCounter(Duration)
If Duration = 0 Then
TextBox2.Text = Now.ToString()
tmr.Stop()
End If
End Sub
End Class

Use a Stop Watch, it provides a set of methods and properties that you can use to accurately measure elapsed time.
Shared Sub Main(ByVal args() As String)
Dim stopWatch As New Stopwatch()
stopWatch.Start()
Thread.Sleep(10000)
stopWatch.Stop()
' Get the elapsed time as a TimeSpan value.
Dim ts As TimeSpan = stopWatch.Elapsed
' Format and display the TimeSpan value.
Dim elapsedTime As String = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
Console.WriteLine( "RunTime " + elapsedTime)
End Sub 'Main

There are two readily available Timer object alternatives:
System.Threading.Timer (explained here, my first pick)
System.Timers.Timer (explained here)

Related

How to make a countdown timer that a custom control

I am trying to create a count down timer control that I will be adding to a bigger project later. The control I am trying to make is a countdown timer that is given an initial value of 60 secs but also allows the user to change that value if needed. I am doing this in Visual Studio using Visual Basics.
Public Class UserControl1
Dim timeTick As Integer
Dim min As Integer
Dim setSecs As Integer = 60
Dim sec As Integer = 120
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
sec -= 1
min = sec % 60
Label1.Text = min & " : " & sec
If sec < 60 Then
min = 1 + timeTick
Label1.Text = min & " : " & sec
End If
End Sub
Property HowLong As Integer
Get
Return setSecs
End Get
Set(value As Integer)
setSecs = value
End Set
End Property
End Class
Set your Timer Interval to something less than one second; I used 250.
Then store the time in the future that is XXX seconds away, representing your countdown duration.
At each tick, simply subtract the current time from the stored future time to get a TimeSpan. Update your label with the TimeSpan value using ToString().
When the HowLong property is changed, update the target time and restart your timer...easy peesy.
All together, it'd look something like this:
Public Class UserControl1
Private target As DateTime
Private setSecs As Integer = 60
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
target = DateTime.Now.AddSeconds(HowLong)
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Dim ts As TimeSpan = target.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
Label1.Text = "-" & ts.ToString("mm\:ss")
Else
Label1.Text = "00:00"
Timer.Stop()
End If
End Sub
Property HowLong As Integer
Get
Return setSecs
End Get
Set(value As Integer)
setSecs = value
Timer.Stop()
target = DateTime.Now.AddSeconds(HowLong)
Timer.Start()
End Set
End Property
End Class
The authors response:
Technically your way will work to I will post my solution below I did
it slightly differently. – Thomas
From my comments on the authors own submission:
The problem with this type of approach is that the Timer control is
not accurate. It is only guaranteed to not fire before the interval
has transpired. In fact it will almost always fire after the interval
with some extra "slop". For short periods (seconds/minutes), you won't
notice. For longer periods (hours), you will, as the accumulated slop
becomes bigger as time passes. Whether this matters is completely
dependent upon your application. – Idle_Mind
Technically speaking, here's a quick example of how inaccurate simply incrementing/decrementing a counter using a 1 second Timer can be:
' Timer1.Interval was set to 1000 (timer fires every "second")
Private seconds As Integer = 0
Private start As DateTime = DateTime.Now
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds = seconds + 1
Label1.Text = seconds
Label2.Text = DateTime.Now.Subtract(start).TotalSeconds
End Sub
After only 1 hour and 15 minutes, the counter method on the left is already off by 4 seconds from the actual time that has passed:
A key advantage of the DateTime/TimeSpan method is that the time calculation is independent from the Timer. That is to say that the frequency at which the Timer fires has no bearing on how accurate the time calculation is.
This code below is how I made a simple timer control that countdown from a set value. Also, it has 2 buttons that pause and resume the time. This control will not work if in design mode and the timer interval is set to 1000. If you have any questions about how it works just leave a comment.
Public Class UserControl1
Dim timeRemaing As Integer = 60
Private Sub UserControl1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer.Start()
End Sub
Private Sub Timer_Tick(sender As Object, e As EventArgs) Handles Timer.Tick
Dim sec As Integer
Dim mins As Integer
Dim timerFormat As String
If Not Me.DesignMode Then
sec = timeRemaing Mod 60
mins = timeRemaing \ 60
If sec < 10 Then
timerFormat = mins.ToString + ":0" + sec.ToString
Else
timerFormat = mins.ToString + ":" + sec.ToString
End If
If timeRemaing > 0 Then
timeRemaing -= 1
lblTime.Text = timerFormat
Else
Timer.Stop()
lblTime.Text = "The Time has Stop!!!"
End If
End If
End Sub
Public Property HowLong As Integer
Get
Return timeRemaing
End Get
Set(value As Integer)
If value <= 0 Then
Timer.Stop()
ElseIf value > 0 Then
Timer.Start()
timeRemaing = value
End If
End Set
End Property
Private Sub btnPause_Click(sender As Object, e As EventArgs) Handles btnPause.Click
Timer.Stop()
End Sub
Private Sub btnResume_Click(sender As Object, e As EventArgs) Handles btnResume.Click
Timer.Start()
End Sub
End Class

Issue with Progressbar in VB2012

I am trying to add a ProgressBar to my program. The program basically compares two values of time and when the values are equal a MessageBox appears to indicate that time is up. I need the ProgressBar to load based on the time difference of the two values. One of the values in a clock and the other is input by the user (similar to an alarm).
My code:
Imports System.Net.Mime.MediaTypeNames
Public Class Form1
Private hour As Integer = 0
Private minute As Integer = 0
Private second As Integer = 0
Public Sub show_time()
second += 1
If second = 59 Then
second = 0
minute += 1
If minute = 59 Then
minute += 1
hour += 1
End If
End If
Label3PrgressStdPC.Text = hour.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= minute.ToString.PadLeft(2, "0") & ":"
Label3PrgressStdPC.Text &= second.ToString.PadLeft(2, "0")
Label3PrgressStdPC.Refresh()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
show_time()
If TextBox1.SelectedText = TextBox1.Text Then Exit Sub
If TextBox1.Text = Label3PrgressStdPC.Text Then
Timer1.Stop()
MsgBox("time is up")
End If
End Sub
Private Sub Bn_start_St01_Click(sender As Object, e As EventArgs) Handles Bn_start_St01.Click
Timer1.Start()
Timer1.Enabled = True
Timer2.Start()
Timer2.Enabled = True
End Sub
**Private Sub ProgressBar1_Click(sender As Object, e As EventArgs) Handles ProgressBar1.Click
ProgressBar1.Maximum = , the max progrssbr will be determine by user input
ProgressBar1.Minimum = 0**
End Sub
**Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
progresbar1.value = ,Not so sure how to write the logic here**
End Sub
End Class
Can anyone help me out i am really getting frustrated.....thanks
How about something like this...
Private Ticker As Timer = New Timer 'Create a timer
Private Start As DateTime 'Store when we start
Private Expire As DateTime 'and when we end
'Call this to get things going
Sub Begin(EndHour As Integer, EndMinute As Integer, EndSecond As Integer)
Start = DateTime.Now
'If input is a time today ...
Expire = DateTime.Now.Date.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'or just a number of hours/mins/secs from now...
Expire = DateTime.Now.Add(New TimeSpan(EndHour, EndMinute, EndSecond))
'When the timer fires, call Tick()
AddHandler Ticker.Elapsed, Sub() Tick()
Ticker.Enabled = True
Ticker.Interval = 1000
Ticker.Start
End Sub
Private Sub Tick()
If DateTime.Now < Expire Then
'Not Finished
Dim Elapsed = DateTime.Now.Subtract(Start)
Dim TotalMillis = Expire.Subtract(Start).TotalMilliseconds
Dim ProgressDouble = Elapsed.TotalMilliseconds / TotalMillis
'Me.Invoke is used here as the timer Tick() occurs on a different thread to the
'one used to create the UI. This passes a message to the UI telling it to
'update the progress bar.
Me.Invoke(Sub()
ProgressBar1.Value = CInt(ProgressDouble * ProgressBar1.Maximum)
Label3PrgressStdPC.Text = Elapsed.ToString
End Sub)
Else
'Done
MessageBox.Show("Done")
Ticker.Stop
End If
End Sub
See VB.NET Delegates and Invoke - can somebody explain these to me? for more information on Invoking.

Progressbar decrement using datetime

I am trying to decrement timer from 30 minutes to 0 mins and update the progressbar with the decrement of time
I have a progressbar control on my form and set it's min val to '0' and max value to '60' and incremental step to '1'
I have stucked with it right now..
This is what I have done so far:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ProgressBar1.Value = 60
End sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
Dim dFrom As DateTime
Dim dTo As DateTime
Dim sDateFrom As String = DateTime.Now
Dim sDateTo As String = lblLogOutTime.Text
If RemainingTime.Text = "00:00:00" Then
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
ElseIf DateTime.TryParse(sDateFrom, dFrom) AndAlso DateTime.TryParse(sDateTo, dTo) Then
Timer2.Start()
ProgressBar1.Value -= 1
ProgressBar1.Update()
Dim TS As TimeSpan = dTo - dFrom
Dim hour As Integer = TS.Hours
Dim mins As Integer = TS.Minutes
Dim secs As Integer = TS.Seconds
Dim timeDiff As String = ((hour.ToString("00") & ":") + mins.ToString("00") & ":") + secs.ToString("00")
RemainingTime.Text = timeDiff
End If
It seems like you have a lot of extra code in there. For instance DateTime types converted to string, then back to Date.
Private LogOutTime as Date ' destination time
Form Load/Restart sub:
LogOutTime = DateTime.Now.AddMinutes(30)
' 1 min tick
Timer2.Interval = 60 * 1000 ' 1 min timer
ProgressBar1.Value = 30 ' 30 min countdown
ProgressBar1.Maximum = 31
Timer2.Start
Private Sub Timer2_Tick(...
Dim Ts as TimeSpan = LogOutTime - DateTime.Now
If Ts.Minutes = 0 Then ' or TS,Ticks
RemainingTime.Text = "Time's up!"
ProgressBar1.Value = 0
Timer2.Stop()
Exit Sub
End If
' better to convert Ts.Ticks to a 0-30 value
' so the timer interval can be different than 1 min
ProgressBar1.Value -= 1
RemainingTime.Text = New DateTime(Ts.Ticks).ToString("hh:mm:ss")
Timer2.Start()
End Sub
There are several ways to format the time remaining depending on your .NET version. I dont know what Timer1 does, it might interfere. If the Timer interval was 20 or 30 secs you could show seconds ticking away but you'd have to calculate the progressbar value from Timespan.Ticks rather than simply decrement.

Timer to count down in VB.Net 2010?

I'm trying to use a timer to count down from a specified time I choose with the time being separated into minutes and seconds using the format MM:SS and then stop when the time reaches 00:00.
So far I've used a previous answer that was found on here and modified it to the best of my knowledge with counting down although I've hit a snag in which when the timer successfully starts counting down, it's delayed and out of sync when counting down the minutes.
For example, counting down from 120 seconds;
02:00 >
02:59 >
02:58 >
02:57 >
02:56 >
02:55
And then when continuing to count down past 90 seconds under the same test;
02:30 >
01:29 >
01:28 >
01:27 >
01:26 >
01:25
When the countdown reaches 00 or 30 seconds, it incorrectly displays the minutes left and can't understand or figure out how to fix it.
Here is my code for my Counting Timer;
Private Sub tmrCountdown_Tick(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles tmrCountdown.Tick
SetTime = SetTime - 1
lblTime.Text = FormatTime(SetTime)
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub
Here is my code for the Function formatting the time;
Public Function FormatTime(ByVal Time As Integer) As String
Dim Min As Integer
Dim Sec As Integer
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
And here is my code for the Form Load;
Private Sub frmSinglePlayer_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
'Setting the time.
SetTime = 120
lblTime.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
End Sub
I've set;
Dim SetTime As Integer
At the top of my Public Class so I am able to input a specified time into the countdown timer. This is probably something incredibly silly and I can't figure out what it is.
Any help is greatly appreciated and please bare in mind, I am a beginner at programming and get easily confused with large walls of code. (I can barely understand the Function as it is.)
Thank you for helping!
Play with this:
Public Class frmSinglePlayer
Private TargetDT As DateTime
Private CountDownFrom As TimeSpan = TimeSpan.FromMinutes(3)
Private Sub frmSinglePlayer_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmrCountdown.Interval = 500
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrCountdown.Start()
End Sub
Private Sub tmrCountdown_Tick(sender As Object, e As System.EventArgs) Handles tmrCountdown.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTime.Text = ts.ToString("mm\:ss")
Else
lblTime.Text = "00:00"
tmrCountdown.Stop()
MessageBox.Show("Done")
End If
End Sub
End Class
Take a tested sample of countdown timer. Make the changes you need(ex the format of the time).
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
SetTime = 70
AddHandler dtTimer.Tick, AddressOf dtTimer_Tick
dtTimer.Interval = New TimeSpan(0, 0, 1)
dtTimer.Start()
End Sub
Private Property SetTime As Integer
Private Sub dtTimer_Tick(sender As Object, e As EventArgs)
Dim iMinutes As Integer
Dim iSeconds As Integer
If SetTime = 0 Then
dtTimer.Stop()
txtTime.Text = "0:0"
Exit Sub
End If
SetTime -= 1
iMinutes = Math.Floor(SetTime / 60)
iSeconds = SetTime Mod 60
txtTime.Text = iMinutes & ":" & iSeconds
End Sub
Try this
'the amount of time to countdown from
Dim countDownFrom As New TimeSpan(0, 0, 10) 'ten seconds
'a Stopwatch to track how long running
Dim stpw As New Stopwatch
Private Sub Button1_Click(sender As Object, _
e As EventArgs) Handles Button1.Click
Timer1.Interval = 250 'how often to update display
Timer1.Start() 'start the display updater
stpw.Reset() 'restart the stopwatch
stpw.Start()
'or depending on version of .Net
'stpw.Restart
End Sub
Private Sub Timer1_Tick(sender As Object, _
e As EventArgs) Handles Timer1.Tick
If stpw.Elapsed <= countDownFrom Then
Dim toGo As TimeSpan = countDownFrom - stpw.Elapsed
lblTime.Text = String.Format("{0:00}:{1:00}:{2:00}", toGo.Hours, toGo.Minutes, toGo.Seconds)
Else
Timer1.Stop()
stpw.Stop()
End If
End Sub
your mistake in your original code is that you are using the MOD operater incorrectly.
'Minutes
Min = ((Time - Sec) / 60) Mod 60
'Seconds
Sec = Time Mod 60
At 2:00 you see 2:00 because:
Min = ((120-00) / 60 ) MOD 60 = 2 MOD 60 = 2
Sec = 120 MOD 60 = 0
At 1:59 you see 2:59 because
Min = (119 / 60) MOD 60 = 1.98 MOD 60 = 1.98 = 2
Sec = 119 MOD 60 = 59
After 31 seconds your minutes changes from 2 to 1 because
Min = (89 / 60) MOD 60 = 1.48 MOD 60 = 1.48 = 1
More simply:
Format((Math.Floor(lSeconds / 60)), "00") & ":" & Format((lSeconds Mod 60), "00")
Public SetTime As Integer = 0
Public Min As Integer = 0
Public Sec As Integer = 0
Public Decimaal As Decimal = 0
Public Function FormatTime(ByVal Time As Integer) As String
'Minutes
Min = Fix(SetTime / 60000)
'Decimaal
Decimaal = (SetTime / 60000) - Min
'Seconden
Sec = Fix(Decimaal * 60)
Return Format(Min, "00") & ":" & Format(Sec, "00")
End Function
Private Sub tmrCountdown_Tick(sender As Object, e As EventArgs) Handles tmrCountdown.Tick
SetTime = SetTime - 1000
lblCountdown.Text = FormatTime(SetTime)
tmrCountdown.Enabled = True
If SetTime = 0 Then
tmrCountdown.Enabled = False
End If
End Sub
You could just do
For i = 120 to 0 step -1
Console.writeline(i)
Next
But be aware it will instantly put them on the screen and it won't do it 1 at a time

VB.NET Timer Interval 1 = 1 millisecond?

I Got a Timer With Interval = 1
Interval 1 = 1 millisecond ?
if Interval 1 is not 1 millisecond ,So tell me which control interval = 1ms
code:
Imports System.Globalization
Public Class Form1
'Default Time To Start From
Dim time As String = "00:00:00,000" 'Start From Here
'Label
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.Click
Timer1.Start() 'Run The Timer On Click
End Sub
'TIMER
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'Timer Interval = 1
Dim ci = CultureInfo.InvariantCulture
Dim original As TimeSpan = TimeSpan.ParseExact(time, "hh\:mm\:ss\,fff", ci) 'ParseExact
Dim difference As TimeSpan = TimeSpan.FromMilliseconds(1) ' = 1 Millisecond
Dim final = original
final = original + difference ' connect between original to difference !(00:00:00,000 + 1 MS = 00:00:00,001)!
Dim output As String = final.ToString("hh\:mm\:ss\,fff", ci) 'convert to the format ( = 00:00:00,001 ) (Back It To The Right Format)
time = output '!!Update!! the Time String from 00:00:00,000 To 00:00:00,001 |||| And in the Next Time 00:00:00,001 + 1 = 00:00:00,002
Label1.Text = time 'Show the Time String in the label
End Sub
End Class
As you see - Im Useing Regular Timer With Interval 1 , But i think that it worng because timer not counting milliseconds
if you got advice ,tell me.
The description of the interval property from MSDN is:
Gets or sets the time, in milliseconds, before the Tick event is
raised relative to the last occurrence of the Tick event.
However (as Steve pointed out in his comment):
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
Taken from http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx
The System.Timers.Timer class referred to is described here: http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Imports System.Globalization
Public Class Form1
Dim time As String = "00:00:00:00"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim ci = CultureInfo.InvariantCulture
Dim original As TimeSpan = TimeSpan.ParseExact(time, "dd\:hh\:mm\:ss", ci) 'ParseExact
Dim difference As TimeSpan = TimeSpan.FromSeconds(1) ' = 1 Millisecond
Dim final = original
final = original + difference ' connect between original to difference !(00:00:00,000 + 1 MS = 00:00:00,001)!
Dim output As String = final.ToString("dd\:hh\:mm\:ss", ci) 'convert to the format ( = 00:00:00,001 ) (Back It To The Right Format)
time = output '!!Update!! the Time String from 00:00:00,000 To 00:00:00,001 |||| And in the Next Time 00:00:00,001 + 1 = 00:00:00,002
Label1.Text = time 'Show the Time String in the label
End Sub
End Class
Here's working script. IDK why it works but it works! :)