Program SomeDaemon;
{...}
TdaMyDaemon = Class(TCustomDaemon)
Private
MyThread : TMyThread;
FLog : TEventLog;
procedure StartLog;
Procedure ThreadStopped (Sender : TObject);
public
FTermRTLEvent: PRTLEvent;
function LoadSettings: boolean;
constructor Create(AOwner: TComponent);override;
destructor Destroy;override;
Function Start : Boolean; override;
Function Stop : Boolean; override;
Function ShutDown : Boolean; override;
Function Install : Boolean; override;
Function UnInstall: boolean; override;
end;
constructor TdaMyDaemon.Create(AOwner: TComponent);
begin
FMyThread:=nil;
inherited.Create(AOwner);
FTermRTLEvent := RTLEventCreate;
end;
destructor TdaMyDaemon.Destroy;
begin
RTLeventDestroy(FTermRTLEvent);
inherited Destroy;
end;
function TdaMyDaemon.Start: Boolean;
var
OK: boolean;
begin
Result:=inherited Start;
StartLog;
OK:=LoadSettings;
If OK then begin
if not (Assigned(FMyThread)) then begin
FMyThread:=TMyThread.Create(FConfigFile,FLog,@ThreadStopped);
if Assigned(FMyThread.FatalException) then
raise FMyThread.FatalException;
end;
FMyThread.Start;
end else begin
Application.Log(etError,'cannot create MyThread, check settings');
end;
Result:=OK;
end;
function TdaMyDaemon.Stop: Boolean;
var
OK: boolean;
I: integer;
begin
Result:=inherited Stop;
Application.Log(etDebug,' TdaMyDaemon.Stop: Assigned(FMyThread)='+BoolToStr(Assigned(FMyThread),true));
If (Assigned(FMyThread)) then
begin
Application.Log(etDebug,' TdaMyDaemon.Stop: Assigned(FMyThread.OnTerminate)='+BoolToStr(Assigned(FMyThread.OnTerminate),true));
FMyThread.Terminate;
I:=0;
// Wait at most 10 seconds.
While (FMyThread<>Nil) and (I<10000) do
begin
//Sleep(100); //causes temporary hang?
RTLeventWaitFor(FTermRTLEvent, 100);
inc(i);
ReportStatus;
end;
// Let the thread die silently. Not sure about this.
{
If (FMyThread<>Nil) then
FMyThread.OnTerminate:=Nil;
}
end;
OK:=FMyThread=Nil;
Application.Log(etInfo,'DaemonStop: OK='+BoolToStr(OK,true));
Application.Terminate;//Not sure about this. I hoped this solves: exe stays is memory after stopping the service.
end;
procedure TdaMyDaemon.ThreadStopped(Sender: TObject);
begin
Application.Log(etInfo, 'Thread Stopped');
if (Assigned(FMyThread)) then
begin
FreeAndNil(FMyThread);
Application.Log(etDebug, 'Thread freed');
end;
end;