在vb.net中安排任务的最佳方法

时间:2013-05-14 11:09:47

标签: vb.net timer cron

我需要在小时和半小时执行命令行。 有没有比这更好的方法呢?也许那些不涉及每秒检查小时的那些。

间隔1秒的计时器:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        For i As Integer = 0 To 24
            If TimeString = i & ":00:00" & i Then or TimeString = "0" & i & ":00:00 or If TimeString = i & "30:00:" & i Then or TimeString = "0" & i & ":30:00

            End If
        Next
End Sub

2 个答案:

答案 0 :(得分:1)

步骤1 - 计算从现在到下一个小时或半小时标记的时间;

步骤2 - 将计时器的经过时间设置为等于步骤1中计算的时间;

步骤3 - 当计时器滴答时,将经过的时间重置为30分钟,然后完成您需要做的工作。

如果进程必须在小时/半小时内完全运行,则重新计算步骤3中所需的时间,而不是将其设置为30分钟(这将补偿漂移)。

这是一些计算到午夜的毫秒数的代码;你应该可以在那里工作

Private Function MillisecondsToMidnight() As Integer

    Dim ReturnValue As Integer
    Dim ts As TimeSpan

    Dim Tomorrow As DateTime = Today.AddDays(1)
    ts = Tomorrow.Subtract(Now)

    ReturnValue = ts.TotalMilliseconds()

    ts = Nothing
    Return ReturnValue

End Function

答案 1 :(得分:0)

你的问题非常有趣。我认为现在所需的功能完全在下面实现。我测试了它,我相信它有效。

假设您使用Button1触发整个功能,并且您想使用我们拥有的Timer组件:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim seconds As New Integer()
    Dim minutes As New Integer()
    seconds = System.DateTime.Now.TimeOfDay.Seconds
    minutes = System.DateTime.Now.TimeOfDay.Minutes
    Dim firstOccurrence As TimeSpan = TimeSpan.Zero
    Do
        If seconds.Equals(60) Then
            Exit Do
        Else
            seconds = seconds + 1
            firstOccurrence = firstOccurrence + TimeSpan.FromSeconds(1)
        End If
    Loop

    Do
        If minutes.Equals(59) Or minutes.Equals(29) Then
            Exit Do
        Else
            minutes = minutes + 1
            firstOccurrence = firstOccurrence + TimeSpan.FromMinutes(1)
        End If
    Loop

    Timer1.Interval = (((firstOccurrence.Minutes) * 60) + ((firstOccurrence.Seconds))) * 1000
    Timer1.Enabled = True


End Sub 

Private Sub Timer1_Tick(发送者为对象,e为EventArgs)处理Timer1.Tick

    'execute your code here
    Timer1.Interval = 30 * 60 * 1000

End Sub