VB .NET每天在指定的时间运行一个线程

时间:2014-09-09 08:31:21

标签: .net vb.net multithreading timer scheduled-tasks

我试图每24小时运行一次后台线程,但我想在每天上午10点的特定时间运行它。

 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

如下所示,我需要在上午10点之前调用线程,而不是像下面那样简单地进行24小时的休眠。我知道一种方法可能是检查像Hour(Date.Now)= 10和Minute(Date.Now)= 0这样的东西,但我想这不是一个正确的方法来做到这一点。

Private Sub DoStuffThread()
    Do
        DO things here .....
        Threading.Thread.Sleep(24 * 60 * 60 * 1000)
    Loop
End Sub

2 个答案:

答案 0 :(得分:0)

运行良好的调度程序应用程序将是您最好的选择。你不需要自己编写。

我不明白你为什么要把优先级设置为高。

有更好的方法可以做到这一点,但这是一个快速的例子,需要对你的代码进行一些修改。 我们的想法是存储下一个执行日期,看看当前日期是否已通过。

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

答案 1 :(得分:0)

我认为以这种方式做起来会更简单:

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
相关问题