unit Scheduler;

interface

uses
  HandleComponent,
  Windows, Messages, Classes, SysUtils, Forms;

const
  WU_Notify = WM_User + 1;

type
  TSchedulerEvent = procedure (Sender:TObject; ATick:cardinal) of object;

  TScheduler = class (THandleComponent)
  private
    FOldTick : cardinal;
    procedure on_WU_Notify(var Msg:TMessage); message WU_Notify;
  private
    FActive: boolean;
    FOnNotify: TSchedulerEvent;
  public
    destructor Destroy; override;

    procedure Start;
    procedure Stop;
  published
    property Active : boolean read FActive;
    property OnNotify : TSchedulerEvent read FOnNotify write FOnNotify;
  end; 

implementation

{ TScheduler }

destructor TScheduler.Destroy;
begin
  Stop;

  inherited;
end;

procedure TScheduler.on_WU_Notify(var Msg: TMessage);
var
  Tick, Term : cardinal;
begin
  if FActive = false then Exit;

  Tick := GetTickCount;
  if Tick < FOldTick then Term := 0
  else Term := Tick - FOldTick;

  FOldTick := Tick;

  Application.ProcessMessages;
  if Assigned(FOnNotify) then FOnNotify(Self, Term);
  Application.ProcessMessages;

  if FActive then PostMessage(Handle, WU_Notify, 0, 0);
end;

procedure TScheduler.Start;
begin
  if FActive = true then Exit;

  FActive := true;
  FOldTick := GetTickCount;
  PostMessage(Handle, WU_Notify, 0, 0);
end;

procedure TScheduler.Stop;
begin
  FActive := false;
end;

end.
