In Delphi, you can create a timer using a separate thread. One common approach is to use the TThread
class and synchronize the timer events with the main thread. Here’s a simple example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
unit ThreadTimer; interface uses Classes, SysUtils, Windows; type TTimerThread = class(TThread) private FInterval: Integer; FOnTimer: TNotifyEvent; protected procedure Execute; override; public constructor Create(Interval: Integer; OnTimer: TNotifyEvent); property Interval: Integer read FInterval write FInterval; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; implementation { TTimerThread } constructor TTimerThread.Create(Interval: Integer; OnTimer: TNotifyEvent); begin inherited Create(False); FreeOnTerminate := True; FInterval := Interval; FOnTimer := OnTimer; end; procedure TTimerThread.Execute; begin while not Terminated do begin Sleep(FInterval); Synchronize( procedure begin if Assigned(FOnTimer) then FOnTimer(Self); end ); end; end; end. |
Here, TTimerThread
is a thread class that runs an infinite loop, sleeping for a specified interval and then executing the timer event. The Synchronize
method ensures that the timer event is executed in the context of the main thread.
To use this timer, you can create an instance of TTimerThread
in your main form or unit, and handle the timer event in the main thread:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ThreadTimer; type TForm1 = class(TForm) Memo1: TMemo; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private TimerThread: TTimerThread; procedure TimerEvent(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin TimerThread := TTimerThread.Create(1000, TimerEvent); // 1000 ms interval end; procedure TForm1.FormDestroy(Sender: TObject); begin TimerThread.Terminate; TimerThread.WaitFor; TimerThread.Free; end; procedure TForm1.TimerEvent(Sender: TObject); begin Memo1.Lines.Add(‘Timer event at ‘ + TimeToStr(Now)); // Perform actions in response to the timer event end; end. |
In this example, the timer fires every 1000 milliseconds (1 second), and the TimerEvent
method is executed in the main thread. Adjust the interval and the timer event handling code according to your needs.
Leave a Reply