Dynamic Timer Class

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

This class allows you to wait a specific time (like Sleep) AND maintain a responsive UserInterface (UI).

screen-shot

It works like a:

  While (Now < waitTill) : DoEvents : Wend

- loop but doesn't eat up all your system time like the above loop.

Why not use the Timer Control?

Well first, the timer control ist limited to a maximum 65 second intreval while this timer can handle intervals up to 2147483647 ms (that's just a bit less that 25 days).

Second: with a timer control it is difficult to so something like this:

   ..code runs ...
   Wait 10Secs
   ... continue code ..

Third: This class has a Cancel method to stop waiting a once.

Why should you use the Timer control?

CWaitNDispatch can do some unpretty things to your callstack when running. When you call wait on a timer object and then call wait on another while the first one is still running, the second one won't return until the "first" one has finnished. (See the example in the form).

Usage:

  • Instantiate an object of the class CWaitNDispatch.
  • Call the "Wait" function with the number of milliseconds you want to wait as parameter.
  • Call "Cancel" to stop waiting

ATTENTION:

When you call Cancel from a messagehandler (i.e. Command1_Click, Form_Unload) the code after the "Wait" call will continue AFTER you leave the message handler!

So don't call cancel in the Unload event because your app will not terminate then.

Call Cancel in QueryUnload and set the Cancel parameter of QueryUnload to true if timer.IsWaiting returns true.

Download Zipped TimerClass (18k)

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read