Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net NET在指定的时间每天运行一个线程_.net_Vb.net_Multithreading_Timer_Scheduled Tasks - Fatal编程技术网

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

.net NET在指定的时间每天运行一个线程,.net,vb.net,multithreading,timer,scheduled-tasks,.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

我试图运行一个背景线程每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小时。我知道一种方法可能是检查小时(Date.Now)=10和分钟(Date.Now)=0,但我想这不是一种正确的方法

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

运行一个好的调度程序应用程序是最好的选择。你不需要自己写

我不明白你为什么要把优先权定得很高

有更好的方法可以做到这一点,但这里有一个简单的示例,只需对代码进行少量修改。 其想法是存储下一个执行日期,并查看当前日期是否已传递给它

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
Private子DoStuffThread()
Dim nextExecution作为日期时间
nextExecution=DateTime.Now
nextExecution=新日期时间(nextExecution.Year,nextExecution.Month,nextExecution.Day,10,0,0)
如果nextExecution
我认为这样做会更简单:

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

既然您已经标记了它
计划任务
为什么还要尝试重新发明轮子,而不仅仅是使用Windows提供的内置计划程序?您的问题的答案是使用计划任务。还有为什么
Background DoStuff Thread
具有
ThreadPriority.Highest
?@Filburt我是VB新手,不太确定该走哪条路。你能给我举一个使用任务调度器的例子吗?Thanks@wuha在Windows平台上创建计划任务不需要任何编程知识-请参阅开始。您的VB程序将是任务将在配置的触发器(每天上午10点)执行的操作。@Filburt好吧,实际上我需要通过编程来完成。谢谢,这正是我想要的!