18

I am new to working with Windows Services. Although I have learnt to create Windows Services in VS2010 I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.

superM
  • 7,373

13 Answers13

42

A service runs in the background, even if no-one is signed on to the machine. Anything you can imagine wanting to do without relying on a person to start an app and click a button is a good candidate for a service. For example, monitoring a folder and whenever a file is written to it, process it in some way. Any "server" you can think of - web server, ftp server, mail server - is a service, and so are many background processes you may not often think of.

Some things that were once written as services (backup files at 2am, send reminder emails at 3am etc) are probably better done today as scheduled tasks, which have tremendous flexibility on Windows 7 and up, but if the developer never learned them, or the system must support XP, you will also find services doing those sorts of tasks.

Kate Gregory
  • 17,495
9

Services on Windows are basically programs that run without a GUI. Web servers (such as apache), database servers (such as mysql & sql server), anti-virus engines, and application/'middleware' servers are all practical examples of applications that often run as services. There may be GUI client to allow you to interact with the service, but the service itself doesn't have one. It just runs 'in the background', doing its thing. In addition, since services run with the user rights assigned to them, they can run as their assigned user whether or not a user is actually logged into the machine. So a database server would have the same access rights regardless of the person logged into the machine at the time, if any. So you can see why that'd be important - you dont want to have to keep a user logged in to keep a web server running, for example.

They are the Windows equivalent (in most practical ways) to Daemons on *nix.

GrandmasterB
  • 39,412
5

Service

A program, routine, or process that performs a specific system function to support other programs, particularly at a low (close to the hardware) level. When services are provided over a network they can be published in Active Directory, facilitating service-centric administration and usage.

I would like to know some practical ways in which windows services could be used?

As per the service defination, Window Service and others type of services do lots of functionality. In this context search engines are your friend.

Windows services are normally used when an application needs to continuously run. You should create a Windows Service to run code in the background, without user interaction.

A Windows Service will run even if no-one is logged on. Windows service can start running as soon as the machine is powered up, which makes ideal for running as a server, http server for example. No one is required to login.

For example if they need to:

  1. Wait for incoming requests. (Like through remoting or wcf)
  2. Monitor a queue, file system etc.If a program just needs to run periodically, like once a day. It is normally easier to create a scheduled task..
  3. Any server that accepts connections (such as a mail, web, or FTP server) should usually be a Windows Service.

I would use a service for the following reasons:

  • You don't need to have a session running. This is good for security, and also reduces overhead on the server.
  • You get some of the management commands built in for free
    o Start
    o Stop
    o Pause
    o Continue

  • You can handle server events such as shutdown.

Links with additional information about these services:

At Asp.net - //TODONT: Use a Windows Service just to run a scheduled process
What is use of WIndows Service

Niranjan Singh
  • 1,283
  • 9
  • 14
4

An interactive program, like a winform or WPF, is something you want a user to open, interact with, and close. A scheduled Task is something you want to run in the background as specific times - maybe just start up, do something, and stop. A Windows Service is something you want to run all the time in the background.

Some advantages of a Windows Service is that it runs no matter which user is logged in (or even if no users are logged in) and it can be set to start running as soon as the computer boots up, which can be really useful if the system is rebooted.

I've usually used services when I have to monitor something like a folder or email inbox.

allen.mn
  • 305
3

Since you added the note about practical examples to your question, I will give you some examples of services I have written for enterprise applications (you don't say if you are an enterprise applications programmer but my guess is that most C# VS2010 programmers are). I think you are looking for an idea of what developers that don't work for Microsoft might write.

A heartbeat monitor service that checked if other programs were still running (this might have worked as a scheduled task as well, but was implemented as a service).

A report writing service that worked through queues of report requests, ran the reports, and sent them to different printers depending on what printer was busy. This helped offload a fair amount of work from a legacy application and allowed the report running to be shared by multiple cheap boxes running the service.

It was implemented as a service so that it would run continuously, start automatically on a reboot, and be able to use the standard windows services interface to start, stop, pause, etc. Also, if it was a scheduled task it would need to initiate getting data from other programs or a persistent source (a queue, a file, a database) rather than being available for other program's to call (socket, pipe).

The server portion of a that client/server application was also implemented as a service so that it would restart on a reboot, etc. There was another project with an .exe that ran the same program not as a service, to make it easier to debug on development machines.

I hope that helps. The other answers are better general answers though, especially the idea that scheduled tasks are probably easier to write and administer for most purposes now.

psr
  • 12,866
2

There are many practical uses for a service. One main practical use is the interaction between UI and service (or daemon in unix) programs, which is, in this case, the difference between a client and a server. A server receives requests, processes the request, and usually sends back a reply. In other words, it SERVES a request. Think about SQLSERVER, IIS, or telnet. A client, usually utilizes a server by sending requests to the server and then displaying or processing the reply. i.e. A data entry application, a web application ... The server is almost always installed as a service in windows (or a daemon in unix) and the client is usually just a normal app with a gui. There are many more complex uses of a service, but this is the one you will probably use the most.

For example: I am currently working on a SIP/H323 video server. It receives requests from an application using an SDK that I wrote, processes them, and replies back. The video server application is installed as a daemon on an embeded linux machine (it would be a service on an embeded Windows machine, but who uses Windows for embeded anyways) and any application utilizing the SDK would be considered a client.

Of course, you could write such applications and not make them a service. You could still make them start upon starting Windows and have them run in the background. However, it involves several registry entries and some finagling in your code--it is much easier to do using the c api than in something like .NET. Microsoft has on the other hand, made this much easier by creating services and allowing us to register them with the O.S. It is much simpler and easier to implement than doing it manually.

2

Examples of candidate programs:

  • Systems that must monitor resources/other applications and send reports (user activity, particular kinds of file traffic, notifications of application misbehaviour)

  • Systems that offer services to other local applications (translations, file conversion, inter-system messaging)

  • Anti-virus software.

I think these are the big examples that can't easily be done using scheduled tasks.

linkerro
  • 687
2

My favorite examples of using services:

  1. Servers - programs that serve requests from remote clients. They will usually run as services to make sure that they are available no matter if any user is logged in to the server or not. Running as a service also means that the server starts processing requests as soon as the machine is started, no one has to log in to the machine to start the program after the machine is restarted for any reason. A database server is a great example.
  2. Background processing - programs that are responsible for processing data from a data source and storing results into a data target. The data target is often a source for another process, and so on. Running as services allows those programs to just sit there and wait for the data to arrive. It also lets developers improve the robustness of the processing by splitting the process into multiple semi-independent steps.
2

Here's a sample usage of the service concept with real code (se below).

What it does is to configure a service bus that consumes off of a queue and listens to messages from web servers and client GUIs.

When it receives the messages it does what logic the domain warrants, it saves the events to disk and publish those events to the message broker.

Most larger applications that are loosely coupled implement some sort of "worker" architectures like the thing below.

The Documently project is a sample project that we have created for people like yourself to learn distributed architectures with. You can ask questions directly to me in the project, or fork it and implement some feature to learn from and then submit a pull request (and get code comments).

https://github.com/haf/Documently/blob/master/src/Documently.Domain.Service/Program.cs:

using System.Threading;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Documently.Infrastructure;
using Documently.Infrastructure.Installers;
using MassTransit;
using Topshelf;
using log4net;
using log4net.Config;

namespace Documently.Domain.Service
{
    class Program
    {
        private static readonly ILog _Logger = LogManager.GetLogger(typeof (Program));

        private IWindsorContainer _Container;
        private IServiceBus _Bus;

        public static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Domain Service Main Thread";
            HostFactory.Run(x =>
            {
                x.Service<Program>(s =>
                {
                    s.ConstructUsing(name => new Program());
                    s.WhenStarted(p => p.Start());
                    s.WhenStopped(p => p.Stop());
                });
                x.RunAsLocalSystem();

                x.SetDescription("Handles the domain logic for the Documently Application.");
                x.SetDisplayName("Documently Domain Service");
                x.SetServiceName("Documently.Domain.Service");
            });
        }

        private void Start()
        {
            XmlConfigurator.Configure();
            _Logger.Info("setting up domain service, installing components");

            _Container = new WindsorContainer()
                .Install(
                    new RavenDbServerInstaller(),
                    new CommandHandlerInstaller(),
                    new EventStoreInstaller(),
                    new BusInstaller(Keys.DomainServiceEndpoint)
                    );

            _Container.Register(Component.For<IWindsorContainer>().Instance(_Container));
            _Bus = _Container.Resolve<IServiceBus>();

            _Logger.Info("application configured, started running");
        }

        private void Stop()
        {
            _Logger.Info("shutting down Domain Service");
            _Container.Release(_Bus);
            _Container.Dispose();
        }
    }
}
Henrik
  • 634
2

Some time ago my team implemented 3 windows services on a bank here in Brazil, as below:

  • Interface between systems: We had a front-office application responsible of booking trades on the stock market, and a back-office application, responsible for accounting and calculating the trades fees. Initially, the intersystem communication was made directly on SQL Server, but too many locking and retention problemas made the system suffer from poor performance. A service was implemented to connect to both front and back databases and do the proper reading/writing using some kind of retention strategy (instead of writing every single trade on the SQL Server, we hold the data to some extend, say 1000 trades, and did a bulk insert, which was 40x faster than the original solution, and did not lock many of the involved tables for a long time).

  • Message Queue: Along with the previous solution, we wrote a custom message queue handler, so several batch processing procedures could run asynchronously. That was integrated with both MSMQ and IBM-MQSeries.

  • Centralization of business services: Several user applications needed common data as stock prices, for example, so we wrote a custom service responsible for receiving "price requests" and sending back the price information.

One of the aspects that led us to write services, instead of "robots", is that services can run as a specific user (as someone already pointed out on this thread), and can be initiated automatically when the machine boots up.

Services also do not need a desktop or a window management service to run. They can run on the background (well, they must run on the background).

And, if you are like some peers of mine that do not like to write user interfaces, services are great technological challenges, because usually they must not fail. So it's very fun to write a service. :)

Machado
  • 4,130
0

If you are designing a Windows desktop application that needs to run as standard user but sometimes needs to perform a task that requires admin privileges you can use a service.

Your installer installs the service with the needed permissions, your desktop application calls in to the service when it needs to perform a task with admin privilege.

There are security implications to this approach that are beyond the scope of this answer.

Jim In Texas
  • 1,453
0

For programmers the primary reason for using service is:

  • This program needs to start automatically on a Windows machine after a reboot.

Anything you write which must conform to the above must run as a Windows Service.

0

The most useful service I've written, from the end-user perspective:
* User printed UGLY invoices on a dot-matrix printer with RAW print-driver.
* User wanted a PRETTY invoice with logo, smooth-line graphics.
* No access to legacy code.

The service would:
* Monitor (multiple) printer folders for print jobs.
* Create a PDF of the invoice.
* PDF would "underlay" a nice blank invoice image
* Overlay the raw text
* Look up meta data, based on folder being used (IE: printer being used)

Then the metadata would:
* Generate PDF
* and/or print PDF
* and/or file the PDF to a final destination folder
* and/or delete the PDF
* and/or email the PDF invoice to customer

In this case, it handles ghost-script, PLC and PDF engines. It's been running very cleanly for years. Include log files!!!