Windows Service Application in Delphi
What is Windows Service?
Windows
service is an application that runs on background. It is usually used to check
system updates continuously, to work on system resources. Service applications
take requests from client applications, process those requests, and return
information to the client applications. They typically run in the background,
without much user input.
Why do we need it?
Suppose we
have system that needs to respond 24/7 days or if we have software that needs
to update frequently, then we can create service which will check the new
updates and download it. Then update to new software. In such situations we can
use Window Services.
What are the limits?
We cannot
use any visual components in service applications. You can add just any
nonvisual component to the new service. But you’re restricted to nonvisual
components; you'll get an exception Controls Cannot Be Added To A Service
message if you try to drop a visual component
How to create Windows Service in
Delphi?
To create a
service application in Delphi start Delphi IDE and select
File->New->Other. Then select "Service Application". Then you
can see application which includes a Datamodule descendent Tservice class. The
TService class is where we do our stuff and it has a number of properties which
you can see in the Object Inspector.
Note that if you have the Standard
edition of Delphi "Service Application" may not be available. You
need at least the Professional edition.
Configure service application - check object inspector for
property and events.
Properties
AllowPause
and AllowStop properties used to allow Start and Stop
service in Service Control Manager. You need to set these to true.
DisplayName
specifies the name of
the service in the Service Control Manager or Task Manager; enter any name you
want in here.
Interactive
property specifies
whether the Service should be able to communicate with the desktop (for
example, with ShowMessage).
The ServiceStartName and Password properties
specify the user account detail to allow operating the service.
The ServiceType is set to stWin32 for a Win32 Service, and
the StartType property can be stAuto, stBoot,
stDisabled, stManual, or stSystem
Events
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.
OnStartEvent,
OnExecute is an event that is called when the Service is started. This is where
we will write our code to perform some task.
Install & Uninstall Service
Note that
you need administrator rights to install and uninstall service applications,
because it is necessary to write or delete registry entries in HKEY_LOCAL_MACHINE,
and that requires permissions that normal or restricted users do not have.
To install the service: Click Start and
select run, then type: PATHTOYOURSERVICE\yourservicename.exe
/INSTALL /silent then press Enter
To uninstall: Click on Start and select
run, then type: PATHTOYOURSERVICE\yourservicename.exe
/UNINSTALL / silent then press Enter You will see a confirmation dialog
when the service has been successfully uninstalled or an error message if it
failed. It can fail if you do not have sufficient rights.
Note*: /silent If you do not want to see the confirmation dialog you can
add the /silent switch like this:
Open the
Control Panel; go into Administration and into the Services applet. You will
see a list of currently installed services. Locate your service name in the
list, right click on it and select "Start" menu item in the popup
menu. Notice that the Status for the service changes to Started. You can press
the F5 key or select the Refresh command to update the list to make sure that
the service keeps running.
You can also see your service in the Task Manager. Right click on an open area of your task bar at the bottom of your screen, then select "Task Manager", select the Processes tab. Here you can see a list of currently running processes
Writing codes in service application
to do some task
There are
basically two places where you can put your service code: OnExecute or the OnStart
event.
OnExecute Event:
Put your
code in the TService.OnExecute method to perform some task when service is
executing. Here you can also create a thread with your code if you want.
- Occurs when the thread associated
with the service starts up.
- When the OnExecute event handler
finishes, the service thread terminates.
- Most OnExecute event handlers contain
a loop that calls the service thread’s ProcessRequests method so that other
service requests are not locked out."
Example
procedure
TCompanySqlDatabaseSpecialSomething.ServiceExecute(
Sender: TService);
const
SecBetweenRuns = 10;
var
Count: Integer;
begin
Count := 0;
while not Terminated do
begin
Inc(Count);
if Count >= SecBetweenRuns then
begin
Count := 0;
{ place your service code here }
{ this is where the action happens }
SomeProcedureInAnotherUnit;
end;
Sleep(1000);
ServiceThread.ProcessRequests(False);
end;
end;
OnStart event:
Used in
situation if we want to handle each service request in separate threads. We can
create a new thread (TThread) that contains your code and start the thread in
the TService.OnStart event.
- OnStartup occurs when the service
first starts up, before the OnExecute event.
- This event should be used to
initialize the service. For example, if each service request is handled in a
separate thread (a good idea if handling the request takes much time) the
thread for a request is spawned in an OnStart event handler.
Example
Define a
thread variable in your TService's private section like this:
private
{ Private declarations }
MyServiceThread: TMyServiceThread;
Now you
need to create and fill in the OnStart and OnStop events like this:
procedure TCompanySqlDatabaseSpecialSomething.ServiceStart(
Sender: TService; var Started: Boolean);
begin
{ Create an instance of the secondary thread
where your service code is placed }
MyServiceThread := TMyServiceThread.Create;
{ Set misc. properties you need (if any) in
your thread }
//MyServiceThread.Property1 := whatever;
// and so on
MyServiceThread.Resume;
end;
procedure
TCompanySqlDatabaseSpecialSomething.ServiceStop(Sender: TService;
var Stopped: Boolean);
begin
MyServiceThread.Terminate;
end;
Note* - If you want to create Windows Service application that should response a client application's request with data communication between them, then its better to look for DataSnap server application. As it provides much flexibility to communicate and pass data between client and server. We can deploy a Datasnap application as Service in server also.
This comment has been removed by the author.
ReplyDelete