2013-07-22 85 views
2

我使用向导创建了一个新的Windows Service项目,提出了一些代码,编译它,运行它与/INSTALL,然后我试图启动它使用net start myservice但我有service name not found错误;然后我去了服务中的控制面板,当我尝试开始点击“开始”链接时,显示的对话窗口无限期地冻结在进度条的50%处。为什么我的Delphi服务应用程序不启动?

这是我第一次尝试做一个服务来更新我正在开发的主系统,并且为了测试,我放了一个Timer来告诉每一分钟的时间。任何人都可以注意到什么是错的,为什么它的行为如此呢?

DPR文件有:

{...} 
begin 
    if not Application.DelayInitialize or Application.Installing then 
    begin 
    Application.Initialize; 
    end; 
    Application.CreateForm(TZeusUpdateSevice, ZeusUpdateSevice); 
    Application.Run; 
end. 

PAS文件用:

{...} 
procedure ServiceController(CtrlCode: DWord); stdcall; 
begin 
    ZeusUpdateSevice.Controller(CtrlCode); 
end; 

function TZeusUpdateSevice.GetServiceController: TServiceController; 
begin 
    Result := ServiceController; 
end; 

procedure TZeusUpdateSevice.ServiceAfterInstall(Sender: TService); 
var 
    regEdit : TRegistry; 
begin 
    regEdit := TRegistry.Create(KEY_READ or KEY_WRITE); 
    try 
    regEdit.RootKey := HKEY_LOCAL_MACHINE; 

    if regEdit.OpenKey('\SYSTEM\CurrentControlSet\Services\' + Name,False) then 
    begin 
     regEdit.WriteString('Description','Mantém atualizados os arquivos e as credenciais da Plataforma Zeus.'); 
     regEdit.CloseKey; 
    end; 

    finally 
    FreeAndNil(regEdit); 
    end; 
end; 

procedure TZeusUpdateSevice.ServiceStart(Sender: TService; var Started: Boolean); 
begin 
{ executa os processos solicitados pelo sistema } 
    Timer1.Enabled := True; 
    while not Terminated do ServiceThread.ProcessRequests(True); 
    Timer1.Enabled := False; 
end; 

procedure TZeusUpdateSevice.Timer1Timer(Sender: TObject); 
begin 
    ShowMessage('Now, time is: ' + TimeToStr(Now)); 
end; 
+0

看看[服务应用教程](http://www.tolderlund.eu/delphi/service/service.htm) –

+1

在这里寻找一个基本的服务框架:http://stackoverflow.com/a/ 10538102/800214 – whosrdaddy

+2

您应该使用线程而不是定时器 – whosrdaddy

回答

12

有几个明显的问题:

  1. 您在拥有无限循环OnStart事件。此事件允许您在服务启动时执行一次性操作。该代码属于OnExecute。
  2. 服务无法显示UI,因此ShowMessage无法工作。您需要使用非可视机制来提供反馈。

由于您的OnStart没有返回,因此SCM会将您的服务视为未启动。所以我想上面的第1项是关于为什么你的服务无法启动的解释。

+0

在项目2中,它是否被服务应用程序中主单元的“Interactive”中和? – PSyLoCKe

+1

由于Vista服务在会话0中运行,并且无法显示UI。 –

+0

因此,要解决我的服务,我应该把OnExecute'虽然没有终止做ServiceThread.ProcessRequests(True);或只是'ServiceThread.ProcessRequests(True);'? – PSyLoCKe

相关问题