|Simple NT Service|
|Step 4. Adding a functionality to the NT service module|
With this step we shall add a timer to our service module. This timer will beep every second when the service runs. Go to the service module source and do the following changes with it.
At first, a very important note: do not place a TTimer component onto the service module. 1 It won`t work !
The thing is that the TTimer component lives in the same thread in which it was created. The service module is created by the Application.CreateForm call and this call is executed from the main thread of the application. The service lives in a separate thread and it is not a main thread of application. So the TTimer won`t work in the service thread in spite of it`s placed on service module. In addition the main thread of the service application stops and waits until all services of application are terminated. Due to this reason there will be no OnTimer events at all !
Now you are ready to make necessary changes. At first, add the ExtCtrls unit to the "uses" section of the service module unit. The necessary changes are marked by backgrounf color below.
Now add the Timer variable to the service class. Add the declaration of the Timer event handler too. Necessary changes looks like this:
Now add the implementation of TimerOnTimer method. In this first example it will beep and nothing more. The necessary changes of the "implementation" section should look as follows
Finally add the service OnStart and OnStop handlers. In the OnStart event handler the Timer should be created and its OnTimer property should be set to the TimerOnTimer. In the OnStop event the Timer variable should be free. Because these events occur in the service thread the timer created in such a way will work in the service thread. It will be real " timer-in-service". Use Object Inspector to add the corresponding event handlers to the service module. Add the following code to them:
Now your service is ready. Save project and compile it. With the next steps we`ll install and test it.
|<< | Index | Step 1 | Step 2 | Step 3 | Step 4 | Step 5 | Step 6 | >>|