Reputation: 1739
I am trying to run a background thread every 24 hours but I would like to run it at specific time say 10 am everyday.
Private Sub StartBackgroundThread()
Dim threadStart As New Threading.ThreadStart(AddressOf DoStuffThread)
Dim thread As New Threading.Thread(threadStart)
thread.IsBackground = True
thread.Name = "Background DoStuff Thread"
thread.Priority = Threading.ThreadPriority.Highest
thread.Start()
End Sub
Rather than simply do a sleep for 24 hours as below, I need the thread to be called when 10 am is reached. I know a way may be checking something like Hour(Date.Now) = 10 and Minute(Date.Now) = 0, but I guess it is not a proper way to do this.
Private Sub DoStuffThread()
Do
DO things here .....
Threading.Thread.Sleep(24 * 60 * 60 * 1000)
Loop
End Sub
Upvotes: 0
Views: 6398
Reputation: 83
I think it will be simpler to do it this way:
Private Sub DoStuffThread()
Do
If DateTime.Now.Hour = 10 And DateTime.Now.Minute = 0 Then
DO things here .....
End If
Threading.Thread.Sleep(60 * 1000) ' Sleep 1 minute and check again
Loop
End Sub
Upvotes: 3
Reputation: 12748
Running a good scheduler application would be your best bet. You don't need to write your own.
I don't see why you would want to set thje Priority to high.
There are better ways to do this, but here's a quick example that need little modification on your code. The idea is to store the next execution date and see if the current date was passed it.
Private Sub DoStuffThread()
Dim nextExecution As DateTime
nextExecution = DateTime.Now
nextExecution = New DateTime(nextExecution.Year, nextExecution.Month, nextExecution.Day, 10, 0, 0)
If nextExecution < DateTime.Now Then nextExecution = nextExecution.AddDays(1)
Do
If nextExecution < DateTime.Now Then
DO things here .....
nextExecution = nextExecution.AddDays(1)
End If
Threading.Thread.Sleep(60 * 1000) ' Just sleep 1 minutes
Loop
End Sub
Upvotes: 2