How to get a delphi application (that's running) to do something at a particular time/date

前端 未结 6 1163
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 11:07

My application sits in the system tray when it\'s not being used.

The user can configure events to occur at particular schedule. For example they may way the task p

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-13 11:48

    Another option would be to create a TThread which performs the management of the timer:

    type
      TestThreadMsg = class(tThread)
      private
        fTargetDate : tDateTime;
        fMsg : Cardinal;
      protected
        procedure Execute; override;
        procedure NotifyApp;
      public
        constructor Create( TargetDate : TDateTime; Msg:Cardinal);
      end;
    

    implementation:

    constructor TestThreadMsg.Create(TargetDate: TDateTime; Msg: Cardinal);
    begin
      inherited Create(True);
      FreeOnTerminate := true;
      fTargetDate := TargetDate;
      fMsg := Msg;
      Suspended := false;
    end;
    
    procedure TestThreadMsg.Execute;
    begin
      Repeat
        if Terminated then exit;
        if Now >= fTargetDate then
          begin
            Synchronize(NotifyApp);
            exit;
          end;
        Sleep(1000); // sleep for 1 second, resoultion = seconds
      Until false;
    end;
    
    procedure TestThreadMsg.NotifyApp;
    begin
      SendMessage(Application.MainForm.Handle,fMsg,0,0);
    end;
    

    Which can then be hooked up to the main form:

    const
      WM_TestTime = WM_USER + 1;
    
    TForm1 = Class(TForm)
      :
      procedure FormCreate(Sender: TObject);
      procedure WMTestTime(var Msg:tMessage); message WM_TestTime;
    end;
    
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      TestThreadMsg.Create(IncSecond(Now,5),WM_TestTime);
    end;
    
    procedure TForm1.WMTestTime(var Msg: tMessage);
    begin
      ShowMessage('Event from Thread');
    end;
    

提交回复
热议问题