How to detect when a certain time has passed in VB.net - vb.net

I need a way to finding out when the time from 0 ends up as 4 secs.
My code is as follows:
I have a global variable called weightdelaycount, which is incremented every 1000 intervals.
Private Sub Timer_weightcheck_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer_weightcheck.Tick
weightdelaycount = weightdelaycount + 1
End Sub
Now I have the do while loop that runs infinitely and only stops depending on two conditions. Either the weightchange = True or if the clock = 4 secs.
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
weightdelaycount = 0
Timer_weightcheck.Enabled = True
Do While 1
If (weightchange() = True ) Then
Timer_weightcheck.Enabled = False
Exit Do
End If
If (weightdelaycount = 4) Then
Timer_weightcheck.Enabled = False
Exit Do
End If
Loop
MessageBox.Show(weightdelaycount)
End Sub
From the routine above you see that I'm using exit Do to exit the loop if the two conditions are met. The problem is that if the weightchange() is not True and 4 seconds passed the systems doesn't stop. I can put a delay in there and then it works, but I need to be accurate with the values that I get for the weight from a scale. If I put a delay, then the values will not be accurate. Is there a way to solve this?
Thank you in advance

Instead of using a timer, you could use a stopwatch. This code will loop until 4000ms after the stopwatch has started. You'll never get it to stop exactly on 4000ms because of the time it takes to run through the the Do..Loop(minimal really), but I presume a couple of ms after is close enough.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim weightdelaycount = 0
Dim timer As New Stopwatch
timer.Start()
Do
If (weightchange() = True) Then
timer.Stop()
Exit Do
End If
Loop Until timer.ElapsedMilliseconds > 4000
timer.Stop()
MessageBox.Show(timer.ElapsedMilliseconds)
End Sub

Related

VB.NET Timer stops working after it ticks the first time

the timer in my code stops working after the first tick, I have it set to start ticking every second when the form loads:
Private Sub FormIdleTimeWaster_Load(sender As Object, e As EventArgs) Handles MyBase.Load
timerCPS.Interval = 1000
timerCPS.Start()
End Sub
but after the first tick, it stops working:
Private Sub TimerCPS_Tick(sender As Object, e As EventArgs) Handles timerCPS.Tick
lblCPS.Text = CStr(CPS)
lblTotalHW.Text = CStr(CPS + HWTotal)
End Sub
All the other code refrencing timerCPS is
Me.timerCPS = New System.Windows.Forms.Timer(Me.components)
Friend WithEvents timerCPS As Timer
Nowhere else references timerCPS in my code and I'm not sure what's wrong
I have replicated your code as given in the question and it is working perfectly fine. It is ticking over every second.
I have modified your code to this:
Public Class FormIdleTimeWaster
Private CPS As Integer = 1
Private Sub timerCPS_Tick(sender As Object, e As EventArgs) Handles timerCPS.Tick
CPS += 1
lblCPS.Text = CStr(CPS)
End Sub
Private Sub FormIdleTimeWaster_Load(sender As Object, e As EventArgs) Handles MyBase.Load
timerCPS.Interval = 1000
timerCPS.Start()
End Sub
End Class
I can clearly see the value in the label increasing by one each tick.
The call to timerCPS.Start() is not needed in timerCPS_Tick.
If you still have an issue then there is some other code you haven't shown.

How to do for loop inside a timer tick event vb 2015?

I would like to do a For Loop inside a timer. Since I want to check an array with element row continuously and I cant continue since the loop seems to not move from 0 on tick, is there a way around this?
I first tried this:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
For row = 0 To 9
msgbox(row)
Next
And then I tried another approach, as suggested in an answer
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
row+=1
msgbox(row)
if row = 10 then
timer1.stop()
end if
Next
MsgBox will now output 0++ on tick but does not stop at 10.
Output Picture
Dim row As Integer = -1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RefreshData()
Timer1.Enabled = True
initialize()
End sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
increment()
MsgBox(row)
End sub
Private Sub increment()
If row > 8 Then
row = 0
Else
row = row + 1
End If
'my if else statement for checking array variable(row)
End Sub
With this code msgbox was able to output 0 to 9 and repeat the process since i need it to continuously monitor the array. For some reason though when msgbox is situated at the first line of increment method or on timer tick before increment is called the output stays -1 the whole time dunno why. Anyways thanks for all the input as im still new to visual basic 2015
Instead of using for loop use a global variable and increment it inside the tick function
Dim ctr as integer = 0
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ctr=ctr+1
row(ctr)
msgbox(row)
if ctr == 10 then
ctr = 0
timer1.stop
end if

How to constantly check for changes in system time?

I'm trying to make a program that makes a sound every hour, how would I do this?
I thought maybe constantly checking the system time and if it's equal to either "1:00 2:00 3:00 etc..." then play a sound, but I don't know how to do this, some help would be appreciated :)
Add a Timer, set Interval for 1000 (1 second) and in Tick event check current time
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
'check time here and put it in Label1
Label1.Text = TimeOfDay.ToString("hh:mm:ss")
'if currenttime = alarmtime then do something
If TimeOfDay.ToString("hh:mm:ss") = "10:01:00" Then Beep()
End Sub
For more info how to read current time:
https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.dateandtime(v=vs.110).aspx
Create a timer, set the interval for 500 milliseconds (.5s), setting to 1 second could cause the tick to be missed. This will fire the tick event, check if the current time minutes and seconds are equal to zero, then fires. The timer is disabled between the sound firing in case the timer checks again within the second (because the timer is called ever half a second).
ReadOnly _tmr As New Timer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
_tmr.Interval = 500
AddHandler _tmr.Tick, AddressOf tmr_Tick
_tmr.Enabled = True
End Sub
Private Sub tmr_Tick(sender As Object, e As EventArgs)
Dim curDateTime As DateTime = Now
If curDateTime.Minute = 0 And curDateTime.Second = 0 Then
_tmr.Enabled = False
PlaySound()
_tmr.Enabled = True
End If
End Sub
Private Sub PlaySound()
'// Play Sound
End Sub

vb.net timer logic (nesting timers)

I've written an app in VB.net that captures data from my PicoScope USB oscilloscope.
It polls the 'scope using a timer, so for example it will poll every 'x' seconds (which is working fine).
However - I also want an option to be able to have this 'x' poll to only run for 'y' minutes, and then stop polling.
I'm having a problem understanding how to nest the timing loops (if nesting is the right option).
This is my code;
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Counter = Counter + 1
Label6.Text = Counter.ToString
Call ReadScope()
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
Counter = Counter + 1
Label6.Text = Counter.ToString
' Call sub
' need to call routine below elsewhere
' I think this is where I need to loop timer 1
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click.
' THIS WORKS
If y <= 0 Then
' here I want standard capture
Call CaptureInterval()
Else
' then here I want capture interval
Call CaptureDuration()
End If
End Sub
' AND THEN I HAVE (which works)
' This is the 'x' timer
Private Sub CaptureInterval()
' this works
If x <= 0 Then
MsgBox("Capture interval not set!")
Return
End If
Me.Timer1.Interval = TimeSpan.FromSeconds(x).TotalMilliseconds
Me.Timer1.Start()
End Sub
' then I have the 'y' timer
Private Sub CaptureDuration()
' this doesn't work
MsgBox("Reached capture duration")
' might need a while timer2 here...
Me.Timer2.Interval = TimeSpan.FromSeconds(y).TotalMilliseconds
Me.Timer2.Start()
' Me.TimerStop()
' I think I need the code below in this loop.
' or just Call CaptureInterval() as below - but in this timer loop
' Call CaptureInterval()
' THIS IS WHERE I'M STUCK!
If x < 1 Then
MsgBox("Capture interval not set!")
Return
End If
While Me.Timer1.Interval < y
Me.Timer1.Interval = TimeSpan.FromSeconds(x).TotalMilliseconds
Me.Timer1.Start()
End While
End Sub
Public Sub ReadScope()
' contains the processing to read the scope data
End Sub
Thanks in advance.
Try this example - there is a form with a single timer and then add the code below. In order to satisfy:
I also want an option to be able to have this 'x' poll to only run for
'y' minutes, and then stop polling.
You just need to set _MaxTicks = (Y minutes * 1000) / _TickInterval.
Public Class Form1
Private _MaxTicks As Integer = 10
Private _TickCount As Integer = 0
Private _TickInterval As Integer = 1000
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Timer1.Interval = _TickInterval
AddHandler Me.Timer1.Tick, AddressOf TimerTick
_TickCount = _MaxTicks
Me.Timer1.Start()
End Sub
Private Sub TimerTick()
Debug.Print(_TickCount)
If _TickCount = 0 Then
Me.Timer1.Stop()
MessageBox.Show(String.Format("Time elapsed is roughly {0} ms", _MaxTicks * _TickInterval))
End If
_TickCount -= 1
End Sub
End Class
I added the following to the timer code.
Variable 'y' is the test duration, which I can select using a numeric control.
If it's greater than '0' then the if loop is activated, and will stop the timer when the counter (IntervalTimer) matches 'y'.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
IntervalTimer = IntervalTimer + 1
Label6.Text = IntervalTimer.ToString
If y >= 0 Then
If IntervalTimer.ToString = y Then
Me.Timer1.Stop()
End If
End If
Call ReadScope()
End Sub
Please note that the variable "Counter" in the code posted originally has changed to "IntervalTimer".

Delaying in VB.net

my issue is i need to wait 3-4 seconds after a button has been pressed before i can check for it, here is my code under button1_click:
While Not File.Exists(LastCap)
Application.DoEvents()
MsgBox("testtestetstets")
End While
PictureBox1.Load(LastCap)
I think i'm doing something really simple wrong, i'm not the best at VB as i'm just learning so any explaining would be great!
~Thanks
If the reason you are needing to wait is for the file to be created try using a FileSystemWatcher and respond to the Created and Changed Events that way you are responding to an event rather than arbitrarily waiting a select period of time.
Something like:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
FileSystemWatcher1.Path = 'Your Path Here
FileSystemWatcher1.EnableRaisingEvents = True
'Do what you need to todo to initiate the file creation
End Sub
Private Sub FileSystemWatcher1_Created(sender As Object, e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created, FileSystemWatcher1.Changed
If e.Name = LastCap Then
If (System.IO.File.Exists(e.FullPath)) Then
FileSystemWatcher1.EnableRaisingEvents = False
PictureBox1.Load(e.FullPath)
End If
End If
End Sub
You can use, although not recommended:
Threading.Thread.Sleep(3000) 'ms
This will wait 3 seconds, but also block everything else on the same thread. If you run this in the form your user-interface will not response until the wait is over.
just as a side note: use MessageBox.Show("My message") instead of MsgBox (latter is from old VB).
If you want your form to continue to function while the 3 seconds pass, you can add a Timer control instead, with some code like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' set the timer
Timer1.Interval = 3000 'ms
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
'add delayed code here
'...
'...
MessageBox.Show("Delayed message...")
End Sub
Drag and drop a Timer control from your toolbox to your form. It's not visible at runtime
or better yet making a wait function using stop watch, this wont halt the process in the same thread like thread sleep
' Loops for a specificied period of time (milliseconds)
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
usage
wait(3000)
for 3 sec delay
You could use this
Public Sub BeLazy()
For i = 1 To 30
Threading.Thread.Sleep(100)
Application.DoEvents()
Next
End Sub
It will delay for 3 seconds.