Service applications let you check for updates on a system or monitor system resources, without interrupting your work. While they can be difficult to create, Delphi makes it simple. This article explains how to create a simple Windows service application in Delphi, which you can build on and modify to suit your own needs.
Creating a Windows Service in Delphi - The Code (Page 3 of 5 )
Once you’ve set up the properties, switch to the events tab. Let's go through the event options:
Before Install, After Install and Uninstall allow you to create actions that will take place during these events.
Start, Stop, Pause, and Continue are all key events that let you interact with the Service from the Service Control Manager or Task Manager. You can start, stop or pause the service in the Service Control Manager.
OnExecute is an event that is called when the Service is started. This is where we will write our code skeleton.
Now that we’ve covered the properties and events that enable you to create a Service application, let’s start to build our service.
Double click onExecute and add the following code:
procedure TService1.ServiceExecute(Sender: TService); begin Timer1.Enabled := True; while not Terminated do ServiceThread.ProcessRequests(True);// wait for termination Timer1.Enabled := False; end;
All that this procedure does is start up a thread that enables or disables the timer. Next we are going to set the timer and add the code to carry out the simple task, so click on the timer, go to the events tab and double click on onTimer, and add the following code:
procedure TService1.Timer1Timer(Sender: TObject); const FileName = 'c:\logdate.txt'; var F: TextFile; begin AssignFile(f,FileName); if FileExists(FileName) then Append(f) else Rewrite(f); writeln(f,DateTimeToStr(Now)); ShowMessage(DateTimeToStr(Now)); CloseFile(f); end;
That’s it as far as the code is concerned. Remember to remove the ‘ShowMessage(DateTimeToStr(Now));’ line in the TService1.Timer1Timer procedure, to avoid getting a MessageBox every minute. Now, all we need to do is first, compile the code (to compile – press Ctrl +F9), then install the service and give it a test run!