【问题标题】:VB .NET run a thread at specified time everydayVB .NET 每天在指定时间运行一个线程
【发布时间】:2014-09-09 08:31:20
【问题描述】:

我尝试每 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

【问题讨论】:

  • 既然你已经标记了它scheduled-tasks,你为什么还要尝试重新发明轮子而不是仅仅使用Windows提供的内置调度程序?
  • 您的问题的答案是使用计划任务。还有为什么Background DoStuff ThreadThreadPriority.Highest
  • @Filburt 我是 VB 新手,不太确定该走哪条路。您能否就我使用任务调度程序的情况举一个例子?谢谢
  • @wuha 在 Windows 平台上创建计划任务不需要任何编程知识 - 请参阅 Schedule a task 开始。您的 VB 程序将是任务将在配置的触发器(每天上午 10 点)处执行的操作。
  • @Filburt 好吧,实际上我需要以编程方式进行

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


【解决方案1】:

我认为这样做会更简单:

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

【讨论】:

  • 这是天才。它消除了对调度程序的需求......只要您在很长一段时间内没有内存泄漏。注意 0 是午夜。 23 日是晚上 11 点。第一分钟是 0。最后一分钟是 59。看起来很明显,但知道这些事情永远不会有坏处。
【解决方案2】:

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

我不明白您为什么要将优先级设置为高。

有更好的方法可以做到这一点,但这里有一个简单的示例,您的代码几乎不需要修改。 这个想法是存储下一个执行日期并查看当前日期是否已过。

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

【讨论】:

  • 谢谢,这正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-29
  • 2020-01-13
  • 2019-05-23
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多