Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Why not use the timer component? This assumes that you are using a GUI and not building a service.</p> <p>You could call a synchronization routine that performed the polling to get the timer very close to the seconds changing, then delegate to the timer. You could call the sync routine once a minute or so to make sure that you aren't getting any OS drift.</p> <p>That being said, I'm sure there is a way to detect the seconds changing event, I just don't know how to do it.</p> <p>Update:</p> <p><a href="http://en.csharp-online.net/Delegates_and_Events%E2%80%94Events_and_Delegates" rel="noreferrer">This link</a> has an implementation similar to what I was envisioning. Just modify it so that you are not permanently stuck in a loop and voila! You have your sync routine.</p> <p>Update 2:</p> <p>Based on feedback from Shog9, I think this might be a better approach than polling:</p> <pre><code>Public Class Form1 Private WithEvents clockTimer As New Timer Private currentTime As DateTime = DateTime.MinValue Private Sub ClockTick(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles clockTimer.Tick UpdateTimer() DisplayTimer() End Sub Private Sub UpdateTimer() currentTime = DateTime.Now clockTimer.Stop() clockTimer.Interval = 1000 - currentTime.Millisecond clockTimer.Start() End Sub Private Sub DisplayTimer() lblTime.Text = currentTime.ToString("T") End Sub Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load UpdateTimer() DisplayTimer() End Sub End Class </code></pre> <p>Now, based on my preliminary tests, there is some sort of drift with each Tick event. On my machine, it varied between 12 and 20 milliseconds. If anyone has an idea on how to reliably correct the drift, I would be interested in learning.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload