• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 336
  • Last Modified:

Setting a timer to run on the hour

I have a vb.net program that runs and accomplishes several tasks every 60 minutes.  I am satisfied with how it is working, but it runs every hour from the time I launch the application.  If I launch the application at 8:50 am, it runs then and again at 9:50, etc.  I would like it to run at 9:00, 10:00, etc.  Is there a way to accomplish this with VB.net?
1 Solution
Luis PérezSoftware Architect in .NetCommented:
Set the Interval property of the Timer to 1000 (it will check every 1 second).

In the code, write this:
Private Sub Timer1_Timer(sender As Object, e As System.EventArgs)
    If Date.Now.ToString("HH:mm:ss").EndsWith(":00:00") Then
        'Start the Task
    End If
End Sub

Hope that helps.
Every second would be a bit extreme. I would set it to every minute.
Mike TomlinsonMiddle School Assistant TeacherCommented:
Try something like...
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Interval = MillisecondsToNextHour()
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

        ' ... do something in here ...
        Debug.Print("Tick() Event @ " & DateTime.Now)

        Timer1.Interval = MillisecondsToNextHour()
    End Sub

    Private Function MillisecondsToNextHour() As Double
        Dim dt As DateTime = DateTime.Today.AddHours(DateTime.Now.Hour).AddHours(1)
        Debug.Print("Next Tick @ " & dt)
        Return dt.Subtract(DateTime.Now).TotalMilliseconds
    End Function

End Class

Open in new window

thoecherlAuthor Commented:
Perfect, Idle_Mind.  Thank you.


Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now