You could use a System.Threading.Timer
to do this. Instead of a loop that constantly runs and sleeps, you could set the interval to the Timer
to be the difference between now and the selected time and the TimerCallback
to be the Sub
that does the task work. Setting the timeout to 0 or Timeout.Infinite
will make sure this is only executed once.
EDIT: Example
Dim tcb As TimerCallback = AddressOf DoStuff
Dim t As Timer
Dim execTime As TimeSpan
Dim dtNow As DateTime = DateTime.Now
Dim hc As Integer = HourChoice
Dim mc As Integer = MinuteChoice
If TimeOfDay = "AM" And hc = 12 Then
hc = 0
Else If TimeOfDay = "PM" Then
hc = hc + 12
End If
Dim dtCandidate As DateTime = New DateTime(dtNow.Year, dtNow.Month, dtNow.Day, hc, mc, 0)
If dtCandidate < dtNow Then
dtCandidate.AddDays(1)
End If
execTime = dtCandidate.Subtract(dtNow)
t = New Timer(tcb,Nothing,execTime,TimeSpan.Zero)
Then you just need a Sub to do your task:
Public Sub DoStuff(obj As Object)
'...Do Some Kind of Work
End Sub