Reputation: 101
Trying to write a small app which need to run a task at x-minutes or x-hour. What I'm facing is the way to calculate the x-time in order to run the task at the specified minute or hour.
My app is just simple : one listbox for minutes (1 to 59), and a textbox to input the message to display at the specified time. so when the user select like 50 min, and enter "Hello", the program after 50 minutes, it has to display a messagebox with "Hello" message, and should have multithread to avoid Ui blockade when running one task, another should also be run.
I tried to use For... Loop to count each second, but I'm not getting the expected result.
Dim s as string
For Each s in myVariable
console.writeLine("Message")
Next
Upvotes: 2
Views: 145
Reputation: 32455
If program should display message after selected amount of minutes, then you can use asynchronous approach.
' When combobox value changed
Private Async Sub ComboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim comboBox = DirectCase(sender, ComboBox)
Dim minutesAmount = DirectCast(comboBox.SelectedItem, Integer)
await Task.Delay(minutesAmount * 60000)
MessageBox.Show("Hello")
End Sub
Task.Delay
will wait until given amount of milliseconds is elapsed and continue execution to next line.
await Task.Delay
will not block UI thread
Upvotes: 1
Reputation: 461
you can use Thread.Sleep(milliseconds)
to achieve what you want
Dim s as string = "Hi"
Thread.Sleep(1000)
console.writeLine("Message")
Reference at https://www.dotnetperls.com/sleep-vbnet
Or you can use a Timer
:
Imports Microsoft.VisualBasic
Imports System.Timers
Public Class TimerTest
Shared _timer As Timer
Shared _list As List(Of String) = New List(Of String)
''' <summary>
''' Start the timer.
''' </summary>
Shared Sub Start()
_timer = New Timer(3000)
AddHandler _timer.Elapsed, New ElapsedEventHandler(AddressOf Handler)
_timer.Enabled = True
End Sub
''' <summary>
''' Get timer output.
''' </summary>
Shared Function GetOutput() As String
Return String.Join("<br>", _list)
End Function
''' <summary>
''' Timer event handler.
''' </summary>
Shared Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs)
_list.Add(DateTime.Now.ToString())
End Sub
End Class
Example from https://www.dotnetperls.com/timer-vbnet
You create one timer per click of the button and you're done :)
Upvotes: 1