Link to home
Start Free TrialLog in
Avatar of Richard2000
Richard2000

asked on

Using TTimer in Threads - OnTimer event never fires.

I have created by own thread object by deriving a class from TThread and overrided the Execute method with the code to execute.  As part of the thread code, I want to dynamically create a timer and fire a procedure I have written within the thread (the OnTimer event).  However, the OnTimer event never fires.  How to I get it to work?  This is the code I have written...

timMyTimer: TTimer; // This goes in private section of TMyThread class

This is how I've created the timer at the beginning of the execute method...

timMyTimer := TTimer.Create(Main);
timMyTimer.OnTimer := OnTimerEvent;
timMyTimer.Interval :=1000;
timMyTimer.Enabled := True;

procedure TMyThread.OnTimerEvent(Sender: TObject);
begin
  // This should fire every second, but doesn't!
end;

Thanks

Richard2000
Avatar of DrDelphi
DrDelphi

are you sure your thread is running?

Ttimer class is a thread object and i don't sure if you can run thread objects one inside another.
ASKER CERTIFIED SOLUTION
Avatar of DrDelphi
DrDelphi

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
unit Unit2;

interface

uses
  Classes,extctrls,Dialogs;

type
  TTest = class(TThread)
  private
    { Private declarations }
    Timer:TTimer;
    procedure TimerEvent(Sender:TObject);
  protected
    procedure Execute; override;
    procedure ShowOK;
  public
    constructor Create(CreateSuspended: Boolean);
    destructor  Destroy;override;
  end;

implementation

{ Test }

constructor TTest.Create(CreateSuspended: Boolean);
begin
  inherited;
  Timer:=TTimer.Create(nil);
  Timer.Interval:=1000;
  Timer.OnTimer:=TimerEvent;
end;

destructor TTest.Destroy;
begin
  Timer.Free;
  inherited;
end;

procedure TTest.Execute;
begin
  while Terminated do ;
end;

procedure TTest.ShowOK;
begin
  ShowMessage('Ok');
end;

procedure TTest.TimerEvent(Sender: TObject);
begin
  Timer.Enabled:=False;
  Synchronize(ShowOK);
  Timer.Enabled:=True;
end;

end.