Timer in Visual Basic - vb.net

currently i'm trying to make a timer that require start, resume/pause, and stop method in Visual Basic. But when i adding stop method the timer did stop but not reset the value of timer. And sometimes when i try to start it again, the timer ticking to a minus value (ex: -15:-44:-12). Can you please help me? Any help and suggestions would greatly helping.
This is the code that i've been working lately
Public Class Form1
Dim StartTime As DateTime 'old current time
Dim PauseTime As DateTime 'keep track of the time when the timer is paused
Dim TotalTimePaused As TimeSpan 'The total amount of time paused
Private Sub BtnStart1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart1.Click
BtnStart1.Enabled = False
BtnPause1.Enabled = True
StartTime = DateTime.Now()
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'Subtract the current "Now" time from the start time
'and then subtract the total time paused
Dim ElapsedTime As TimeSpan = DateAndTime.Now.Subtract(StartTime).Subtract(TotalTimePaused)
Label2.Text = ElapsedTime.Hours.ToString.PadLeft(2, "0"c) + ":" + ElapsedTime.Minutes.ToString.PadLeft(2, "0"c) + ":" + ElapsedTime.Seconds.ToString.PadLeft(2, "0"c)
'And if you wanted the total elapsed time from time of start then
'subtract the current "Now" time from the start time only.
End Sub
Private Sub BtnPause1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnPause1.Click
If Timer1.Enabled = False Then
BtnPause1.Text = "Pause"
'Add to the total time paused; the current time minus the
'time of pause. this will be the total amount of time
'paused so you can subtract it from the total amount of
'time since the start button was pressed
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Timer1.Enabled = True
Else
BtnPause1.Text = "Resume"
Timer1.Enabled = False
'Set the pause time so it can be
'calculated to the total time paused.
'when the timer is resumed
PauseTime = DateAndTime.Now
End If
End Sub
Private Sub BtnStop1_Click(sender As Object, e As EventArgs) Handles BtnStop1.Click
If Timer1.Enabled = False Then
BtnStart1.Enabled = True
BtnPause1.Text = "Pause"
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Else
Timer1.Enabled = True
End If
End Sub
End Class

You have this function
Private Sub BtnStop1_Click(sender As Object, e As EventArgs) Handles BtnStop1.Click
If Timer1.Enabled = False Then
BtnStart1.Enabled = True
BtnPause1.Text = "Pause"
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Else
Timer1.Enabled = True
End If
End Sub
where you stop the timer, I think you should change this...
Private Sub BtnStop1_Click(sender As Object, e As EventArgs) Handles BtnStop1.Click
If Timer1.Enabled = True Then
Timer1.Enabled= False 'Here you stop the timer and
'when you clic the start button this starts on
'on your time.
BtnStart1.Enabled = True
BtnPause1.Text = "Pause"
TotalTimePaused = TotalTimePaused.Add(DateAndTime.Now.Subtract(PauseTime))
Else
Timer1.Enabled = False
End If
End Sub
You have to stop the timer when it is running.

Related

vb.net background worker cancel not working

I'm having an issue where BackgroundWorker.CancelAsync() isn't working. I have WorkerSupportsCancellation set to TRUE. I am also polling BackgroundWorker1.CancellationPending in DoWork. Here is sample code of what I am trying to achieve. I have background worker looping through a time stamp and assigning a value to Measurement variable. I have a subroutine that queries the last reported Measurement variable and writes to listbox. After 5 loops I send BackgroundWorker.CancelAsync(). I can see the cancellation is pending, but it doesn't actually cancel the background worker. Is this a race condition?
Public Class Form1
Dim Measurement As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
Delay(0.5)
For x = 1 To 5
ListBox1.Items.Add(Measurement)
ListBox1.TopIndex = ListBox1.Items.Count - 1
TextBox1.Text = BackgroundWorker1.CancellationPending
Delay(1)
Next
BackgroundWorker1.CancelAsync()
TextBox1.Text = BackgroundWorker1.CancellationPending
ListBox1.Items.Add("Cancel Pend: " & BackgroundWorker1.CancellationPending)
Delay(5)
ListBox1.Items.Add("Busy: " & BackgroundWorker1.IsBusy)
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Exit Sub
Else
Do
Measurement = Now()
Loop
End If
End Sub
End Class
You just need to move the check for the cancellation inside the Do...Loop otherwise it will be tested only at the start of the DoWork event handler and never after that
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Else
Do
If BackgroundWorker1.CancellationPending = True Then
e.Cancel = True
BackgroundWorker1.Dispose()
Exit Do
Else
Measurement = Now()
End If
Loop
End if
End Sub

Why does my loop in the timer control stops suddenly VB.net

Now when I have my code in my one project where this is the ONLY code (note, I got a listbox that is full of items around 29 items!), the function works properly and it loops through every single item and gives it out as a messagebox.
When I enter this code into my bigger project where I meticulously copy pasted the code, the loop in the timer stops after 3 times EVERY TIME. Even when I enter in the timer1.
If Count < "29" Then
Still it stops after three times EVERY TIME. What am I doing wrong, the sources are pretty much the same?!
Code:
Public Class Form1
Dim NumberOfItems As Integer
Dim Count As String
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If Timer1.Enabled = False Then
Timer1.Enabled = True
Button2.Text = "Stop Timer"
NumberOfItems = ListBox1.Items.Count
Count = "0"
Else
Timer1.Enabled = False
Button2.Text = "Start Timer"
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Count < NumberOfItems Then
Dim CurrentIt3m As String = ListBox1.Items(Count)
MsgBox(CurrentIt3m)
Count = Count + 1
Else
Button2.Text = "Start Timer"
End If
End Sub
End Class

Count down timer in vb.net

In the following code I have a timer that counts down from 5 mins. I am trying to have a visual count down timer in a lbl in mm:ss but the example I used doesn't work. It counts down but doesn't update the lbl until it hits 00:00.
The asker of the following question (were I got the code) said it works perfectly but for me it doesn't at all.
The Example I used
My code:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
picLogo.SizeMode = PictureBoxSizeMode.StretchImage
'Timer until update
tmrUpdate.Interval = 300000 '5 minutes
TargetDT = DateTime.Now.Add(CountDownFrom)
tmrUpdate.Enabled = True
End Sub
Private Sub tmrUpdate_Tick(sender As Object, e As EventArgs) Handles tmrUpdate.Tick
Dim ts As TimeSpan = TargetDT.Subtract(DateTime.Now)
If ts.TotalMilliseconds > 0 Then
lblTimer.Text = ts.ToString("mm\:ss")
Else
lblTimer.Text = "00:00"
tmrUpdate.Stop()
End If
End Sub
Answer:
Using a Async Sub I had the count down timer running while other stuff was going on in the back ground. This way the app could still be used during the Sub Wait() and this code also displayed the count down timer.
Used one timer on a 1 sec interval.
Private Async Sub DoStuff()
'Doing stuff
timeUpDate = 599
tmrUpdate.Start()
Application.DoEvents()
Await Task.Run(Sub()
Wait()
End Sub)
Loop
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles tmrUpdate.Tick
Dim hms = TimeSpan.FromSeconds(timeUpDate)
Dim m = hms.Minutes.ToString
Dim s = hms.Seconds.ToString
If timeUpDate > 0 Then
timeUpDate -= 1
lblTimer.Text = (m & ":" & s)
Else
tmrUpdate.Stop()
lblTimer.Text = "text"
End If
End Sub
Private Sub Wait()
Threading.Thread.Sleep(600000)
End Sub

Add minutes to an existing countdown timer

how To add minutes to an existing countdown timer like while the timer is counting down I can add 10 mins with a push of a button so the time pluses like if the displayed time is 9.59 with the press of a button the time should display 19.59 and continue counting down
Public Class TIMER
Private alarmtime As Date
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If alarmtime < Date.Now Then
Me.Timer1.Stop()
MessageBox.Show("Time up")
Else
Dim remainingtime As TimeSpan = Me.alarmtime.Subtract(Date.Now)
Me.Label1.Text = String.Format("{0}:{1:d2}:{2:d2}", _
remainingtime.Hours, _
remainingtime.Minutes, _
remainingtime.Seconds)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If RadioButton1.Checked = True Then
Me.alarmtime = Date.Now.AddHours(TextBox1.Text)
Me.Timer1.Start()
ElseIf RadioButton2.Checked = True Then
Me.alarmtime = Date.Now.AddMinutes(TextBox1.Text)
Me.Timer1.Start()
ElseIf RadioButton3.Checked = True Then
Me.alarmtime = Date.Now.AddSeconds(TextBox1.Text)
Me.Timer1.Start()
End If
End Sub
Private Sub GameTIMER_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
its just a basic countdown timer it works fine all I need for it to do is add minutes to it while its is counting down because when the timer is up I have to click the text box type in the number then press ok then the timer starts so instead off writhing in the textbox I just want to press a button and the countdown timer automatically adds lets say 10 minutes to current time being displayed while its counting down
If you're talking about a normal Timer, this should be your answer:
Me.Timer1.Interval += (60000 * 10)
EDIT:
Try stopping it first:
Me.Timer1.Stop()
Me.Timer1.Interval += (60000 * 10)
Me.Timer1.Start()

how to run this timer in vb.net?

I want a timer to run on a form whose value is derived from a database. for example when i store the value for the timer in a variable, i multiply it by 60000 to convert milliseconds to minutes. Here is the code:
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim x as integer
details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval =details * 60000
Timer1.Enabled = True
End Sub()
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds.Text = x.ToString
If x= 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
x-= 1
End If
End Sub
When i run this code, the timer runs in the background and when time's up, the form closes. But it doesn't show in the label seconds when timer is ticking. I hope you get what I mean :)
If you want the label to tick the seconds down to 0, you need the timer interval to be 1000, no matter how long you want this to run for.
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval =1000
endTime = DateTime.Now.AddMinutes(details)
Timer1.Enabled = True
End Sub()
Dim endTime As DateTime
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If DateTime.Now > endTime Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
Seconds.Text = (DateTime.Now - endTime).ToString("hh\:mm\:ss")
End If
End Sub
This happens because your timer ticks at Minutes interval. If you want to show seconds in the label then your timer should tick within 1 second interval (maybe a few milliseconds etc.)
So instead of setting Timer1.Interval =details * 60000, set x = details * 60 and Timer1.Interval to 1000.
There is also variable scoping problem with your code. You have declared x as local variable inside Form1_Load, which means that it won't be available inside the Timer1_Tick. Move it outside the procedure.
Dim x As Integer
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval = 1000
x = Details * 60
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
seconds.Text = x.ToString
If x = 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
x-= 1
End If
End Sub
UPDATED
This is assuming that your database saved value is in Milliseconds. Otherwise modify appropriately.
Dim ticker As TimeSpan
Public Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Details = ds.Tables(0).Rows(0).Item("Time")
Timer1.Interval = 1000
ticker = TimeSpan.FromMilliseconds(Details)
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
seconds.Text = String.Format("{0:00}:{1:00}:{2:00}", ticker.Hours, ticker.Minutes, ticker.Seconds)
If ticker.Ticks <= 0 Then
Timer1.Enabled = False
MessageBox.Show("You didn't finish in time.", "Sorry")
Me.Close()
Else
ticker = ticker.Subtract(TimeSpan.FromSeconds(1))
End If
End Sub
This may not be completely what you may want, as I didn't convert the time or anything I just made it as basic as possiable and that way you should be able to work from it :)
Public Class Form1
Dim Time As Integer = 100 'Your time in seconds goes here!
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblTime.Text = Time
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Time = Time - 1
lblTime.Text = Time
If Time = 0 Then
Timer1.Enabled = False
MsgBox("You didn't finish in time.", "Sorry")
Me.Close()
End If
End Sub
End Class
Any problems just message me