I recently found I needed to have an event trigger periodically, and needed it to happen at both a fixed interval, and at particular times. The purpose was to query a broadband modem for signal strength. The requirement for choosing particular times was so that I could compare signal strengths each day at approximately similar times, to see if there was a pattern to the lows and highs.
A search of various forums did not turn up anything except a number of folks that had the same requirement, but had no satisfactory answers.
My solution:
Code:
Private Function getInterval(ByVal MinuteInterval As Integer) As Integer
Dim now As DateTime = DateTime.Now
' duplicate the current time for use as a working variable
Dim later As DateTime = now
Dim interval As TimeSpan
' Add minutes contained in MinuteInterval to the target time
later = later.AddMinutes(CDbl(MinuteInterval ))
'subtract the modulo to get the target time minutes value
later = later.AddMinutes(CInt(-later.Minute Mod MinuteInterval ))
' zero out the seconds in the target time by subtracting the seconds value
' from the target time
later = later.AddSeconds(-later.Second)
' calculate the interval
interval = later - now
' convert the interval to milliseconds and return
' use this interval to set a timer value to trigger at the
' desired time.
getInterval = CInt((interval.Minutes * 60000) + (interval.Seconds * 1000))
End Function
Notes:
This function calculates the number of milliseconds to wait until the next fixed time.
The parameter 'MinuteInterval ' contains the time interval required, and specifies the number of minutes between events, which are assumed to happen (in this example) every 'MinuteInterval' minutes, spread evenly over the hours.
Example: Timer1.interval = getInterval(10)
This will cause Timer1 to trigger at the next even 10 minute mark,
eg. 6:00, 6:10, 6:20, 6:30, 6:40, 6:50, 7:00
If you call the function as above, at 6:23:45, Timer1 will be loaded
with a value that will trigger the timer event at 6:30:00
This is particularly useful when triggering a routine that takes a variable length of time to complete, such as a web document access.
Please feel free to comment or ask questions.
Larry