2009年5月29日

Delphi Windows Service - Indy Time Server


實做 Windows Service, 拿 Indy Time Server 元件來當服務範例

用 Delphi 先建立一個 Service Application
File->New->Other...-> [New page] Service Application

放入 TIdTimeServer 元件
Indy Servers -> IdTimeServer

修改 TService Properties (屬性)
Name = 'DelphiTimeServer'
DisplayName = 'Delphi Time Server'

加入 TService Events (事件)
// OnStart

procedure TDelphiTimeServer.ServiceStart(Sender: TService;
var Started: Boolean);
begin
IdTimeServer1.Active := True;
end;

// OnStop

procedure TDelphiTimeServer.ServiceStop(Sender: TService;
var Stopped: Boolean);
begin
IdTimeServer1.Active := False;
end;

儲存所有檔案 File -> Save All
建立並切換到專案目錄
例如 C:\Borland\Delphi7\Projects\TimeServer

更改預設檔案名稱
Unit1.pas -> TimeServerU.pas
Project1.dpr -> TimeServer.dpr

Complie Project 按 [Ctrl + F9] 編譯執行檔
專案目錄產生執行檔 TimeServer.exe

開啟 DOS 視窗(CMD)並切換到專案目錄
Start->Run...->CMD
例如專案目錄為 C:\Borland\Delphi7\Projects\TimeServer
> cd C:\Borland\Delphi7\Projects\TimeServer

安裝 TimeServer 服務
> TimeServer /install
若安裝成功, 會有對話框 Service installed successfully

啟動服務 DelphiTimeServer
> sc start DelphiTimeServer
SERVICE_NAME: DelphiTimeServer
TYPE : 10 WIN32_OWN_PROCESS
STATE : 2 START_PENDING
(NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0xb97071
WAIT_HINT : 0x1388
PID : 3764
FLAGS :

用 Delphi 建立 Time Client Application
File->New->Application

放入 TIdTime 元件
Indy Servers -> IdTime

修改 TIdTime Properties (屬性)
Host = 'localhost'

加入 TForm Events (事件)
// OnCreate

procedure TForm1.FormCreate(Sender: TObject);
begin
Showmessage(DateTimeToStr(IdTime1.DateTime));
end;

執行程式, 會有對話框顯示目前時間

停止服務 DelphiTimeServer
> sc stop DelphiTimeServer
SERVICE_NAME: DelphiTimeServer
TYPE : 10 WIN32_OWN_PROCESS
STATE : 3 STOP_PENDING
(STOPPABLE,PAUSABLE,ACCEPTS_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x1388

移除 TimeServer 服務
> TimeServer /uninstall
若移除成功, 會有對話框 Service uninstalled successfully

沒有留言:

網誌存檔