Dear Delphi programmers,
I'm looking for help how to write a one-shot timer (No GUI, so VCL Timers out of question)...
Let me explain a little bit more.
In my code (explaining with VCL timer but in this particular project I have no forms):
- Call a
procedure
which send a char over serial port - Enable a timer with a X amount of
Interval
In the OnTimer
event:
I have a code which send a char then disable the timer itself to never be executed again.
The problem is that I need to make the creation of these timers dynamic.
I thought of the function SetTimer()
then KillTimer()
in the "OnTimer event" to disable it (free it).
Is it a good (safe) way?
Thank you!
Do you realize, that you do not have to have a GUI, to use a VCL timer as long as you do have a window handle? You can simply instantiate one from the code by
And even if you don't have a window handle You can create one by calling
but in that case you also have to write your own message loop. I know that calling the Windows API seems to be an easier solution, but it also has its own caveeats (like you can not pass a class method to it...), and I tought, You might want to know about this one.
The multimedia timer API provides support for a one shot timer. The benefit is, that the timing is much more precise than the SetTimer/KillTimer solution and you can use it with intervals <50 ms. This comes at a price, as the callback does not return in the context of the main thread. Here is my implementation of a one-shot timer using the multimedia timer API:
Is it safe to kill timer from inside of a timer event ?
Yes, that's perfectly safe.
How to implement simplest one shot timer ?
The easiest implementation of a 1 second one shot timer is this, but note, that if you start more of them, you won't be able to distinguish which one of them elapsed its interval: