VB.net在计划时间执行任务

问题描述:

我需要在某个时间使用用户输入的小时和分钟执行任务。VB.net在计划时间执行任务

我想的有点像使用某种循环,每一次它循环的,如果检查Now().Hour比赛HourChoiceNow().Minute匹配MinuteChoice

在此,我也有一个用户选项,选择“ AM“或”PM“,如果是TimeOfDay = "PM",则加12小时(Now().Hour是军事时间)。

编辑:我只希望这个运行一次,而不是每一天。

+0

这是一个网络应用程序,桌面应用程序,服务? – randcd

+0

@randcd vb.net桌面应用程序 – user2620851

+0

供参考:[使用VB.net创建计划任务](https://*.com/q/20677722/327083) –

您不必循环,
只需将一个计时器添加到表单中,将其间隔设置为500,以便每500毫秒触发一次。
通过按钮启用它以启动您的任务。

然后在您的Timer.Tick事件:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 
     If Hour(Now) = HourChoice And Minute(Now) = MinuteChoice Then 
      'Your Task Here 
     End If 
    End Sub 
+2

我会创建一个计时器,并将其刻度设置为给定时间等待毫秒。当定时器被调用时,你停止定时器。 –

+0

这是一个更好的方法@DavidSdot –

+0

我如何启用它并设置计时器? – user2620851

你可以使用一个System.Threading.Timer做到这一点。您可以将间隔设置为Timer以代替现在和所选时间之间的差异,并将TimerCallback设置为执行任务工作的Sub,而不是循环不断运行和休眠。将超时设置为0或Timeout.Infinite将确保只执行一次。

编辑:实例

Dim tcb As TimerCallback = AddressOf DoStuff 
Dim t As Timer 
Dim execTime As TimeSpan 
Dim dtNow As DateTime = DateTime.Now 
Dim hc As Integer = HourChoice 
Dim mc As Integer = MinuteChoice 

If TimeOfDay = "AM" And hc = 12 Then 
    hc = 0 
Else If TimeOfDay = "PM" Then 
    hc = hc + 12 
End If 

Dim dtCandidate As DateTime = New DateTime(dtNow.Year, dtNow.Month, dtNow.Day, hc, mc, 0) 

If dtCandidate < dtNow Then 
    dtCandidate.AddDays(1) 
End If 

execTime = dtCandidate.Subtract(dtNow) 
t = New Timer(tcb,Nothing,execTime,TimeSpan.Zero) 

然后你只需要一个子做你的任务:

Public Sub DoStuff(obj As Object) 
'...Do Some Kind of Work 
End Sub 
+0

你能举个例子吗? – user2620851

+0

更新了例子。你不得不原谅我的VB我有点生疏...... – randcd

未经测试,但应该工作。在TimeSpan中,您可以设置日,时,分,秒。

Private timer As System.Threading.Timer = New System.Threading.Timer(AddressOf DoWhatever, Nothing, New TimeSpan(0, 10, 0, 0), -1) 

Private Sub dowhatever(sender As Object, e As Timers.ElapsedEventArgs) 
    ' Do stuff 
End Sub 

更可以在MSDN

有点晚了一个答案到这个问题被发现,但:您可以使用标准System.Windows.Forms.Timer。将时间间隔设置为所需时间与Now()之间的差值(以毫秒为单位),然后启动计时器。