delphi服务应用程序在15秒后停止,计时器不执行

Gan*_*pat 1 delphi service timer

我想在Delphi中制作服务应用程序,每天下午02:00运行和复制一些文件.所以我用过计时器.但控制不会进入计时器事件,服务会在15秒内终止.我在Timer Event上写了一段代码.我怎样才能使用定时服务?请帮忙.提前致谢.

我的代码在这里:

unit untMain;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs, Vcl.ExtCtrls, DateUtils, Vcl.Forms,
untCommon;

type
TsrvBackupService = class(TService)
tmrCopy: TTimer;
procedure tmrCopyTimer(Sender: TObject);

private
strlstFiles : TStringList;
{ Private declarations }
public
{ Public declarations }
end;

var
srvBackupService: TsrvBackupService;

implementation

{$R *.DFM}

procedure ServiceController(CtrlCode: DWord); stdcall;
begin
srvBackupService.Controller(CtrlCode);
end;


procedure TsrvBackupService.tmrCopyTimer(Sender: TObject);
var
strCurTime   : string;
strBKPpath   : string;
strBKPTime   : string;
NowDay       : word;
NowMonth     : word;
NowYear      : word;
NowHour      : word;
NowMin       : word;
NowSec       : word;
NowMilli     : Word;
begin
  DecodeTime(now,NowHour,NowMin,NowSec,NowMilli);
  strCurTime := IntToStr(NowHour)+':'+IntToStr(NowMin);
  strBKPTime := '14:00'
  strBKPpath := ExtractFilePath(Application.ExeName);
  if strCurTime = strBKPTime then begin
     Try
           CopyFile(PChar('c:\datafile.doc'),PChar(strBKPpath + 'datafile.doc'),true);
     except
        on l_e: exception do begin
           MessageDlg(l_E.Message,mtError,[mbOk],0);
        end;
     end;
  end;
end;

end.
Run Code Online (Sandbox Code Playgroud)

mjn*_*mjn 6

而不是计时器,使用在OnStart事件中启动的简单线程.

教程在这里:

http://www.tolderlund.eu/delphi/service/service.htm

TTimer更适合GUI应用程序.他们需要一个消息泵(见这里):

TTimer需要一个正在运行的消息队列才能接收WM_TIMER消息,该消息允许操作系统将消息传递给HWND,或触发指定的回调

  • 大多数人不理解如何正确使用OnExecute事件,因此他们最终意外地使服务死锁和/或导致服务无响应的SCM错误,并想知道为什么.保持OnExecute事件未分配,让TService为您管理SCM交互.使用OnStart事件创建工作线程的建议是最好的方法. (3认同)