user2620851
user2620851

Reputation: 51

VB.net Perform task at scheduled Time

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.

Upvotes: 1

Views: 16677

Answers (4)

Hank
Hank

Reputation: 21

A bit late to add an answer to this question, but: You can use a standard System.Windows.Forms.Timer. Set the interval to the difference in milliseconds beween the required time and Now(), then start the timer.

Upvotes: 0

randcd
randcd

Reputation: 2293

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

Upvotes: 3

Ruben_PH
Ruben_PH

Reputation: 1824

You dont have to loop,
Simply add a Timer to your form, set its interval to 500 so that it fires every 500 milliseconds.
Enable it via a Button to start your Task.

Then on your Timer.Tick Event:

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
       If Hour(Now) = HourChoice And Minute(Now) = MinuteChoice Then
            'Your Task Here
       End If
    End Sub

Upvotes: 2

David Sdot
David Sdot

Reputation: 2333

Not tested but that should work. In the TimeSpan you can set days, hours, minutes, seconds.

Private timer As System.Threading.Timer = New System.Threading.Timer(AddressOf DoWhatever, Nothing, New TimeSpan(0, 10, 0, 0), -1)

Private Sub dowhatever(sender As Object, e As Timers.ElapsedEventArgs)
   ' Do stuff
End Sub

More can be found on MSDN

Upvotes: 0

Related Questions