Delphi implements Windows Services through threads

Source: Internet
Author: User
Problem/question/Abstract: Delphi 5 & 6 has a template project for services, but it is incomplete. this example builds on that template and completes the service. it also shows how to start a thread that beeps every 2 seconds. you can use this as a base when developing servers as services. Answer: This example shows how to use the service template in Delphi, taking it a step further and making a complete example. the source for this is encoded in the ntservice.zip file. coded under D6, but works for D5 if you copy the source parts after creating a template service. below are all the source files listed one by one. to test the source, create a service with Delphi, and PASE these sources on top of the automatically generated source. program ntservice; Uses
Svcmgr,
Ntservicemain in 'Units \ ntservicemain. pa' {exampleservice: tservice },
Ntservicethread in 'Units \ ntservicethread. pa'; {$ R *. Res} begin
Application. initialize;
Application. createform (texampleservice, exampleservice );
Application. Run;
End .{*
Windows Service Template
======================================= Author Kim Sandell
Emali: kim.sandell@nsftele.com disclaimer freeware. Use and Abuse at your own risk. description a Windows NT Service skeleton with a thread.
Works in WinNT 4.0, win 2 K, and Win xp pro the ntservicethread. Pas contains the actual
Thread that is started under the service.
When you want to code a service, put the code in
Its execute () method. Example to test the service, install it into the SCM
The installservice. BAT file. The go to the service
Control Manager and start the service. The interval can be set to execute the example BEEPING
Every X seconds. It depends on the application if it
Needs a Inerval or not. notes this example has the service startup options set
Manual. If you want to make a service that starts
Automatically with windows then you need to change this.
Be carefult! If your application hangs when running as
Service there is no way to terminate the application. History description
========================================================== ====================================
242.169.2002 initial version *}
Unit ntservicemain; interfaceuses
Windows, messages, sysutils, classes, svcmgr,
Ntservicethread; Type
Texampleservice = Class (tservice)
Procedure serviceexecute (Sender: tservice );
Procedure servicestart (Sender: tservice; var started: Boolean );
Procedure servicestop (Sender: tservice; var stopped: Boolean );
Procedure servicepause (Sender: tservice; var paused: Boolean );
Procedure servicecontinue (Sender: tservice; var continued: Boolean );
Procedure serviceshudown (Sender: tservice );
Private
{Private Declarations}
Fservicepri: integer;
Fthreadpri: integer; {internal start & stop Methods}
Function _ startthread (threadpri: integer): Boolean;
Function _ stopthread: Boolean;
Public
{Public declarations}
Ntservicethread: tntservicethread; function getservicecontroller: tservicecontroller; override;
End; var
Exampleservice: texampleservice; implementation {$ R *. DFM} procedure servicecontroller (ctrlcode: DWORD); stdcall;
Begin
Exampleservice. Controller (ctrlcode );
End; function texampleservice. getservicecontroller: tservicecontroller;
Begin
Result: = servicecontroller;
End; Procedure texampleservice. serviceexecute (Sender: tservice );
Begin
{Loop while service is active in SCM}
While not terminated do
Begin
{Process service requests}
Servicethread. processrequests (false );
{Allow system some time}
Sleep (1 );
End;
End; Procedure texampleservice. servicestart (Sender: tservice; var started: Boolean );
Begin
{Default values}
Started: = false;
Fservicepri: = normal_priority_class;
Fthreadpri: = INTEGER (tplower); {set the service priority}
Case fservicepri
0: setpriorityclass (getcurrentprocess, idle_priority_class );
1: setpriorityclass (getcurrentprocess, normal_priority_class );
2: setpriorityclass (getcurrentprocess, high_priority_class );
3: setpriorityclass (getcurrentprocess, realtime_priority_class );
End; {attempt to start the thread, if it fails free it}
If _ startthread (fthreadpri) then
Begin
{Signal success back}
Started: = true;
End
Else
Begin
{Signal Error Back}
Started: = false;
{Stop all activity}
_ Stopthread;
End;
End; Procedure texampleservice. servicestop (Sender: tservice;
VaR stopped: Boolean );
Begin
{Try to stop the thread-signal results back}
Stopped: = _ stopthread;
End; Procedure texampleservice. servicepause (Sender: tservice; var paused: Boolean );
Begin
{Attempt to pause the thread}
If assigned (ntservicethread) and (not ntservicethread. Suspended) then
Begin
{Suspend the thread}
Ntservicethread. Suspend;
{Return results}
Paused: = (ntservicethread. suincluded = true );
End
Else
Paused: = false;
End; Procedure texampleservice. servicecontinue (Sender: tservice;
VaR continued: Boolean );
Begin
{Attempt to resume the thread}
If assigned (ntservicethread) and (ntservicethread. susponded) then
Begin
{Suspend the thread}
If ntservicethread. suincluded then
Ntservicethread. Resume;
{Return results}
Continued: = (ntservicethread. suincluded = false );
End
Else
Continued: = false;
End; Procedure texampleservice. serviceshudown (Sender: tservice );
Begin
{Attempt to stop (terminate) the thread}
_ Stopthread;
End; function texampleservice. _ startthread (threadpri: integer): Boolean;
Begin
{Default result}
Result: = false;
{Create thread and set default values}
If not assigned (ntservicethread) then
Try
{Create the thread object}
Ntservicethread: = tntservicethread. Create (true );
{Set the thread priority}
Case threadpri
0: ntservicethread. Priority: = tpidle;
1: ntservicethread. Priority: = tplowest;
2: ntservicethread. Priority: = tplower;
3: ntservicethread. Priority: = tpnormal;
4: ntservicethread. Priority: = tphigher;
5: ntservicethread. Priority: = tphighest;
End;
{Set the execution interval of the thread}
Ntservicethread. interval: = 2; {start the thread}
Ntservicethread. Resume;
{Return success}
If not ntservicethread. suincluded then
Result: = true;
Except
On E: exception do
; // Todo: exception Logging
End;
End; function texampleservice. _ stopthread: Boolean;
Begin
{Default result}
Result: = false;
{Stop and free thread}
If assigned (ntservicethread) then
Try
{Terminate thread}
Ntservicethread. Terminate;
{If it is suincluded-restart it}
If ntservicethread. suincluded then
Ntservicethread. Resume;
{Wait for it to finish}
Ntservicethread. waitfor;
{Free & nil it}
Ntservicethread. Free;
Ntservicethread: = nil;
{Return results}
Result: = true;
Except
On E: exception do
; // Todo: exception Logging
End
Else
Begin
{Return success-nothing was ever started! }
Result: = true;
End;
End; end .{*
A Windows NT Service thread
======================================== Author Kim Sandell
Email: kim.sandell@nsftele.com
*}
Unit ntservicethread; interfaceuses
Windows, messages, sysutils, classes; Type
Tntservicethread = Class (tthread)
Private
{Private Declarations}
Public
{Public declarations}
Interval: integer; Procedure execute; override;
Published
{Published Declarations}
End; implementation {tntservicethread} procedure tntservicethread. Execute;
VaR
Timeout: integer;
Begin
{Do not free on termination-The Serivce frees the thread}
Freeonterminate: = false; {set interval}
Timeout: = interval * 4; {main loop}
Try
While not terminated do
Begin
{Decrement timeout}
Dec (timeout); If (timeout = 0) then
Begin
{Reset timer}
Timeout: = interval * 4; {beep once per x seconds}
Beep;
End;
{Wait 1/4th of a second}
Sleep (250 );
End;
Except
On E: exception do
; // Todo: exception logging...
End;
{Terminate the thread-This signals terminated = true}
Terminate;
End; end.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.