我想在3 mins
上每小时加上form_load
执行代码。我写了一些代码,但这还不够我的目标。例如,如果我在8:10
打开应用程序,我希望它在9:03
,10:03
,11:03
执行,依此类推。
最佳方法是什么?我尝试使用Timer和下面的代码。
Dim currentDate As DateTime = DateTime.Now
Dim minutesLeft = 60 - currentDate.Minute 'Computes how many minutes left until an hour
Dim toMilisecs = (minutesLeft + 3) * 60000 'Convert (mins + 3) to milisecs
tmrDPL.Interval = toMilisecs 'Set tmrDPL.Interval to toMilisecs
If tmrDPL.Interval = 180000 Then 'Execute every hh:03 hr
'Execute code
End If
答案 0 :(得分:4)
编辑:(考虑当时间分钟在xx:03之前)
您可以使用计时器并在第一次通话后调整其间隔,如下所示:
in form_load:
tick
和计时器If tmrDPL.Interval <> 3600000 Then '60*60*1000
tmrDPL.Interval = 3600000 'next calls must be after one hour from now
End If
DoMyTasks() 'execute your code...
事件:
20001,20002,2003
答案 1 :(得分:2)
这是一个更准确计算开始时间的解决方案。
因为S. Serp的答案并未完全在**:03
启动计时器,而是取决于**:03:59
处应用的开始时间。
Private Sub InitTimer()
Dim currDate As DateTime = Date.Now
Dim startMinute As Integer = 3
Dim startTime As New TimeSpan(currDate.Hour, startMinute, 0)
Dim secondsToNextRun As Integer = (3600 + startMinute * 60) -
((currDate.Minute * 60) + currDate.Second +
If(currDate.TimeOfDay.Ticks > startTime.Ticks, 0, 3600))
'calculate ms from s (add 1ms, for the case that secondsToNextRun = 0)
tmrDLP.Interval = secondsToNextRun * 1000 + 1
tmrDLP.Enabled = True
End Sub
Private Sub tmrDLP_Tick(sender As Object, e As EventArgs) Handles tmrDLP.Tick
If tmrDLP.Interval <> 3600000 Then
tmrDLP.Interval = 3600000
End If
'run your code here
'...
End Sub
答案 2 :(得分:1)
只需几行代码就可以轻松实现这一目标。要做到干净,你必须检查你是否已经通过了触发点,而不仅仅是你刚刚击中它。我写了一个最小的课程来做这件事。如果您想要或根据您的需要进行调整,请使用它。
Public Class OffsetTimer
Private cycle As Long
Private offset As Long
Private nextTrigger As Long
Public Sub New(Byval initCycle As Long, Byval initOffset As Long)
cycle = initCycle
offset = initOffset
'Calculate next trigger point
nextTrigger = offset + ((Date.Now.Ticks / cycle) * cycle)
While(Date.Now.Ticks >= nextTrigger) 'If next trigger time still is in the past...
'offset was to small, so add an additional cycle
nextTrigger = nextTrigger + cycle
End While
End Sub
Public Function CheckTrigger as Boolean
Dim retVar As Boolean
Dim ticks As Long
retVar = False
ticks = Date.Now.Ticks
'If trigger point lies in presence or even past...
If nextTrigger <= ticks Then
'Prepare Return True
retVar = True
'Calculate next trigger point
nextTrigger = nextTrigger + cycle
End If
Return retVar
End Function
End Class
如果已达到CheckTrigger
时间,则True
函数会返回nextTrigger
。
您也可以使用类似的计算来获取下一个触发点(例如Date.Now.Ticks - nextTrigger
)的时间,并为其设置Timer
的间隔。
如果您仍有疑问,请将其留在评论中。