Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understand your question correctly, you want to call a function every minute but have it synchronized with the system clock. This isn't entirely straight forward. I'll tell you my approach and we'll go from there.</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx" rel="nofollow"><code>Timer</code></a> class is a good way of executing a given function at an X interval. The problem with this is you want to keep it in sync with when a minute elapses according to the system clock. So we need to make sure we start the timer only when a minute elapses by the clock. Here are a few approaches.</p> <ol> <li><p>Let the timer fire every second; but before we let it do anything we check to see if a minute has passed according to the clock. If so; then we let it proceed. That would look something like this:</p> <pre><code>Module TimerExample Private _previousTime As DateTime = DateTime.Now Sub Main() Dim timer As New System.Timers.Timer(1000) AddHandler timer.Elapsed, AddressOf TimeElapsed timer.Start() 'Run a loop so the console application doesn't quit Application.Run() End Sub Sub TimeElapsed(sender As Object, args As ElapsedEventArgs) Dim now As DateTime = DateTime.Now If now.Minute &gt; _previousTime.Minute Then 'A minute elapsed. Do your code here Console.WriteLine("A minute elapsed!") End If _previousTime = now End Sub End Module </code></pre> <p>This might be an acceptable solution for you. The only "downside" is that the timer is firing every second; but it doesn't do anything until a minute has elapsed.</p></li> <li><p>Another alternative might be to use two timers. Use the first timer in a similar fasion to the first example; but use it to start another timer that only elapses every minute. Once you start the second timer, let the first one stop. The only positive to this approach is a timer is only firing every minute. The negatives are the timer will probably start drifting from the system clock over a long period of time. The first example is a better approach; but this is an option if letting a timer fire every second is too expensive (though I really doubt it would be).</p></li> </ol> <p>Another thing you may want to handle; maybe not; is when a user changes the system time. You can handle time <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.timechanged.aspx" rel="nofollow"><code>SystemEvents.TimeChanged</code></a> to know when that happens.</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