Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
26  
Practical examples? How about every service running on your Windows box right now? –  Yannis Rizos Feb 1 '12 at 7:25
2  
or every daemon running on your *nix box –  jk. Feb 7 '12 at 10:45
add comment

12 Answers

up vote 40 down vote accepted

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.

share|improve this answer
1  
+1. Great answer. You answer reminds me of how I solved taking database backup. Earlier to take backup we used to run a SQL procedure in the server through a scheduler which calls the exe. The exe used to pop up and then once done is closed by itself. I think a windows service was a better option here. –  Karthik Sreenivasan Feb 1 '12 at 11:41
7  
No, it wouldn't have. That task still doesn't need to listen for connections. Scheduled tasks are the correct way to solve that sort of problem. –  Wyatt Barnett Feb 1 '12 at 12:13
2  
I was running lots of scheduled tasks on NTver < 6.0 too . . . –  Wyatt Barnett Feb 6 '12 at 18:00
1  
@Polynomial: Scheduled tasks can run under any account, at least for anything NT5+. Anything running unattended needs to do logging so you can figure out why it failed. –  Wyatt Barnett Feb 9 '12 at 19:40
1  
Great explanation :). Our current imaging system at the company I work for uses Windows services extensively to handle file processing. From the time the images are scanned into the system to queuing for indexing to archiving and then, finally, to outputting them via email, printing, or fax, it's all Windows services. –  kelleystar Feb 9 '12 at 20:57
show 3 more comments

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

share|improve this answer
add comment

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. :)

share|improve this answer
    
+1 Live example. From all the good answers provided by everyone here I am now getting a better understanding of appropriate use of windows services and I think other programmers will definitely benifit from the knowledge sharing here. Some of the implementations that I had worked in the past could have been better implemented using windows services. –  Karthik Sreenivasan Feb 13 '12 at 15:03
add comment

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.

share|improve this answer
add comment

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();
        }
    }
}
share|improve this answer
    
+1 for illustrating with an example. I shall try implementing your example to get a better understanding. –  Karthik Sreenivasan Feb 13 '12 at 3:43
add comment

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.
share|improve this answer
    
+1 for database server. Things are falling in place. We all use the SqlConnection or OledbConnection to connect to the database which actually is processed by the service that resides in the server. –  Karthik Sreenivasan Feb 10 '12 at 7:12
add comment

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.

share|improve this answer
    
+1 For explaining where windows services are used in detail. I have limited exposure to sockets ( Client-Server model Communicating through IPAddress through ports ) but have not used pipes in general. Do pipes have a similar role to play like sockets do? –  Karthik Sreenivasan Feb 10 '12 at 7:18
add comment

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.

share|improve this answer
    
+1 for the examples. Could you brief on file traffic ? –  Karthik Sreenivasan Feb 9 '12 at 7:25
1  
For instance if you have a web application that sees sporadic spikes in file uploads you would want to alert somebody of them. Also, this applies to any resource that can see spikes at weird times (e.g. web traffic, processor usage) that may not be detected by scheduled checks (due to aliasing). –  linkerro Feb 9 '12 at 7:45
add comment

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.

share|improve this answer
    
If I understand correctly, windows services cannot be called without admin permission? –  Karthik Sreenivasan Feb 7 '12 at 8:22
2  
No, Windows Services cannot be installed or started without admin permissions. But any user can communicate with them if the service is listening (think sockets, named pipes, etc..) –  Eclipse Feb 7 '12 at 15:57
1  
Certainly a standard user can start and call into to a windows service. The service must be installed by an admin user. –  Jim In Texas Feb 8 '12 at 15:51
add comment

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.

share|improve this answer
    
+1 - Just to clarify, the service is hosted in the server as a windows service and then the client SDK sends information to the server via a port to communicate data to receive feedback. Is my understanding correct ? –  Karthik Sreenivasan Feb 7 '12 at 8:46
1  
@Karthik, Are you referring to the design pattern or to my example? If to the former, yes .. or a daemon in Unix. The communication would be some form of TCP/IP. If you are referring to my example, the video server is a daemon on an embeded linux machine. The SDK communicates via a port, the video server has a listening loop which it uses to process the client requests. –  Jonathan Henson Feb 7 '12 at 15:53
    
@Karthik, by the way, it doesn't have to be TCP/IP or Pipes. I have seen people use signals with slots to perform interprocess communication. However, the design pattern is the same. How you communicate is up to the architect of the project. –  Jonathan Henson Feb 7 '12 at 15:55
    
I was referring to the example. –  Karthik Sreenivasan Feb 7 '12 at 15:59
add comment

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.

share|improve this answer
    
+1 - Practical uses. –  Karthik Sreenivasan Feb 7 '12 at 8:24
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.