VB.net 在预定时间执行任务 [英] VB.net Perform task at scheduled Time
问题描述
我需要使用用户输入的小时和分钟在特定时间执行任务.
i need to perform a task at a certain time using the using the user inputted Hour and Minute.
我正在考虑使用某种循环,每次循环时,检查 Now().Hour
是否匹配 HourChoice
和 Now().Minute
匹配 MinuteChoice
I'm thinking of something like using some sort of loop that every time it loops, checks if the Now().Hour
matches HourChoice
and the Now().Minute
matches the MinuteChoice
在这里,我还有一个用户选项来选择AM"或PM",如果 TimeOfDay = "PM"
,添加 12 小时(Now().Hour
是军用时间).
In this, i also have a user option to chose "AM" or "PM", and if TimeOfDay = "PM"
, add 12 hours (The Now().Hour
is military time).
我只希望它一次运行一次,而不是每天运行一次.
I only want this to run once at a time, not every day.
推荐答案
您可以使用 System.Threading.Timer
来做到这一点.您可以将 Timer
的时间间隔设置为现在和所选时间之间的差异,并将 TimerCallback
设置为 Sub
完成任务工作.将超时设置为 0 或 Timeout.Infinite
将确保只执行一次.
You could use a System.Threading.Timer
to do this. Instead of a loop that constantly runs and sleeps, you could set the interval to the Timer
to be the difference between now and the selected time and the TimerCallback
to be the Sub
that does the task work. Setting the timeout to 0 or Timeout.Infinite
will make sure this is only executed once.
示例
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)
那么你只需要一个 Sub 来完成你的任务:
Then you just need a Sub to do your task:
Public Sub DoStuff(obj As Object)
'...Do Some Kind of Work
End Sub
这篇关于VB.net 在预定时间执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!