VB.net Perform task at scheduled Time

vb.net

i need to perform a task at a certain time using the using the user inputted Hour and Minute.

I'm thinking of something like using some sort of loop that every time it loops, checks if the Now().Hour matches HourChoice and the Now().Minute matches the MinuteChoice

In this, i also have a user option to chose "AM" or "PM", and if TimeOfDay = "PM", add 12 hours (The Now().Hour is military time).

EDIT:I only want this to run once at a time, not every day.

Best Answer

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
Related Topic