Execute action every x seconds delphi
I'm trying to execute a function(or procedure) every x seconds.
I've been looking everywhere but never seemed to find something that suits my needs.
My application basically gets data from the web and I want to make an auto-refresh checkbox. So let's say the user checks the box, I want the app to call that f开发者_如何转开发unction every 5 seconds.
Thanks!
Use a TTimer
(from the System
tab in the component palette). Set the interval to the number of seconds * 1000 (converting from milliseconds to seconds), and write a handler for the OnTimer
event.
The simplest way it to use the TTimer component, part of Delphi's standard VCL. Put one on the form, make sure Enabled is set to True, set Interval to 5000 (the value is in milliseconds), and assign its OnTimer event, where you'll put the code that needs to run every 5 seconds.
Sometimes it is a good idea to start with the timer disabled, then set its Enabled property to true in code, so that the timer starts to fire after everything else in your application has been properly set up.
The timer may not be firing in exact 5-second intervals, since timer messages have low priority in Windows and may not be received if the CPU is doing a lot of other work. Since your interval is relatively long, you might set the timer to fire every second (Interval := 1000) or even a few times per second, and check current time every time it fires. Perform the update if current time is later by 5 seconds or more from the time of the last update. (Use the SecondsBetween function in DateUtils unit to make that determination).
I don't have Delphi at the moment, but I'm pretty sure there was a TTimer component in the control palette, and according to this, I think I'm right.
精彩评论