Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleTrigger an event at 5, 10, 15, ... minutes after the hour.
Keywordsalarm, hourly
CategoriesControls
 
Use a Timer. When the Timer fires, calculate the next time to fire the alarm and then set the timer's Interval property to either 60000 or the time it needs to wait, whichever is smaller.
 
Private Sub tmrAlarm_Timer()
Static next_alarm As Date
Dim secs_to_go As Single

    ' See if we have initialized next_alarm.
    If next_alarm = 0 Then
        ' Initialize next_alarm.
        next_alarm = NextAlarmTime
        lblNextAlarm.Caption = Format$(next_alarm, _
            "hh:mm:ss")
    End If

    ' See how many milliseconds until the next
    ' alarm time.
    secs_to_go = DateDiff("s", Now, next_alarm)

    ' Stop the timer to clear previous alarms.
    tmrAlarm.Enabled = False
    
    ' Set the timer's Interval.
    If secs_to_go < 1 Then
        ' Fire the alarm.
        ' *** Do something here ***
        Beep
        
        ' Reinitialize next_alarm.
        next_alarm = NextAlarmTime
    ElseIf secs_to_go < 60 Then
        tmrAlarm.Interval = secs_to_go * 1000
    Else
        tmrAlarm.Interval = 60000
    End If

    ' Restart the timer.
    tmrAlarm.Enabled = True
End Sub
 
The helper function NextAlarmTime calculates the next alarm time. It gets the current time in hours and minutes and then uses some math to calculate the next multiple of 5 minutes.
 
' Return the next time that is a multiple of 5 minutes.
Private Function NextAlarmTime() As Date
' The number of minutes between alarms.
Const ALARM_INTERVAL = 5

Dim time_now As Date
Dim h As Integer
Dim m As Integer
Dim seconds As Long
Dim next_m As Integer

    ' Get the current time.
    time_now = Now

    ' Get the hour and minutes.
    h = DatePart("h", time_now)
    m = DatePart("n", time_now)

    ' Calculate the next multiple of ALARM_INTERVAL.
    next_m = ((m \ ALARM_INTERVAL) + 1) * ALARM_INTERVAL

    NextAlarmTime = DateAdd("n", h * 60 + next_m, Date)
End Function
 
My book Custom Controls Library includes an Alarm control that lets you set alarms far in advance. It demonstrates general techniques for building timer ActiveX controls.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated