windows service vs scheduled task
Asked Answered
S

11

125

What are the cons and pros of windows services vs scheduled tasks for running a program repeatedly (e.g. every two minutes)?

Stratify answered 23/12, 2008 at 22:55 Comment(0)
P
54

Update:

Nearly four years after my original answer and this answer is very out of date. Since TopShelf came along Windows Services development got easy. Now you just need to figure out how to support failover...

Original Answer:

I'm really not a fan of Windows Scheduler. The user's password must be provided as @moodforall points out above, which is fun when someone changes that user's password.

The other major annoyance with Windows Scheduler is that it runs interactively and not as a background process. When 15 MS-DOS windows pop up every 20 minutes during an RDP session, you'll kick yourself that didn't install them as Windows Services instead.

Whatever you choose I certainly recommend you separate out your processing code into a different component from the console app or Windows Service. Then you have the choice, either to call the worker process from a console application and hook it into Windows Scheduler, or use a Windows Service.

You'll find that scheduling a Windows Service isn't fun. A fairly common scenario is that you have a long running process that you want to run periodically. But, if you are processing a queue, then you really don't want two instances of the same worker processing the same queue. So you need to manage the timer, to make sure if your long running process has run longer than the assigned timer interval, it doesn't kick off again until the existing process has finished.

After you have written all of that, you think, why didn't I just use Thread.Sleep? That allows me to let the current thread keep running until it has finished and then the pause interval kicks in, thread goes to sleep and kicks off again after the required time. Neat!

Then you then read all the advice on the internet with lots of experts telling you how it is really bad programming practice:

http://msmvps.com/blogs/peterritchie/archive/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program.aspx

So you'll scratch your head and think to yourself, WTF, Undo Pending Checkouts -> Yes, I'm sure -> Undo all today's work..... damn, damn, damn....

However, I do like this pattern, even if everyone thinks it is crap:

OnStart method for the single-thread approach.

protected override void OnStart (string args) {

   // Create worker thread; this will invoke the WorkerFunction
   // when we start it.
   // Since we use a separate worker thread, the main service
   // thread will return quickly, telling Windows that service has started
   ThreadStart st = new ThreadStart(WorkerFunction);
   workerThread = new Thread(st);

   // set flag to indicate worker thread is active
   serviceStarted = true;

   // start the thread
   workerThread.Start();
}

The code instantiates a separate thread and attaches our worker function to it. Then it starts the thread and lets the OnStart event complete, so that Windows doesn't think the service is hung.

Worker method for the single-thread approach.

/// <summary>
/// This function will do all the work
/// Once it is done with its tasks, it will be suspended for some time;
/// it will continue to repeat this until the service is stopped
/// </summary>
private void WorkerFunction() {

   // start an endless loop; loop will abort only when "serviceStarted"
   // flag = false
   while (serviceStarted) {

      // do something
      // exception handling omitted here for simplicity
      EventLog.WriteEntry("Service working",
         System.Diagnostics.EventLogEntryType.Information);

      // yield
      if (serviceStarted) {
         Thread.Sleep(new TimeSpan(0, interval, 0));
      }
   }

   // time to end the thread
   Thread.CurrentThread.Abort();
}

OnStop method for the single-thread approach.

protected override void OnStop() {

   // flag to tell the worker process to stop
   serviceStarted = false;

   // give it a little time to finish any pending work
   workerThread.Join(new TimeSpan(0,2,0));
}

Source: http://tutorials.csharp-online.net/Creating_a_.NET_Windows_Service%E2%80%94Alternative_1%3a_Use_a_Separate_Thread (Dead Link)

I've been running lots of Windows Services like this for years and it works for me. I still haven't seen a recommended pattern that people agree on. Just do what works for you.

Penates answered 16/11, 2009 at 20:39 Comment(7)
Really you might want to run your service with its own service account. If everything runs a SERVICE or NETWORKSERVICE you are granting permissions to your app that it probably doesn't need (and that can risk the security of not just the one server but your entire network.)Peugia
Indeed. I don't think I stated otherwise?Penates
You kind of implied otherwise in your first paragraph. The user's password is required for services just the same as for the task scheduler if you're not using one of the built-in accounts.Protochordate
@MatthewWhited The NT AUTHORITY\NetworkService is an account with limited privileges.Dissatisfaction
@IanBoyd including any permission assigned to NetworkService related to other applications.Peugia
If you setup your project ti be a windows application instead of a console application - you won't see the MS-DOS windows pop up at allIcosahedron
TopShelf real world sample code? do you use it?Ramose
R
17

Some misinformation here. Windows Scheduler is perfectly capable of running tasks in the background without windows popping up and with no password required. Run it under the NT AUTHORITY\SYSTEM account. Use this schtasks switch:

/ru SYSTEM

But yes, for accessing network resources, the best practice is a service account with a separate non-expiring password policy.

EDIT

Depending on your OS and the requirements of the task itself, you may be able to use accounts less privileged than Localsystem with the /ru option.

From the fine manual,

/RU username

A value that specifies the user context under which the task runs. 
For the system account, valid values are "", "NT AUTHORITY\SYSTEM", or "SYSTEM". 
For Task Scheduler 2.0 tasks, "NT AUTHORITY\LOCALSERVICE", and 
"NT AUTHORITY\NETWORKSERVICE" are also valid values.

Task Scheduler 2.0 is available from Vista and Server 2008.

In XP and Server 2003, system is the only option.

Ragged answered 24/5, 2010 at 4:22 Comment(3)
Please run as Local Service (aka NT AUTHORITY\LocalService) rather than LocalSystem (aka .\LocalSystem). The former has limited rights, while the latter is an administratorDissatisfaction
Yes the additional accounts LocalService and NetworkService are available in schtasks v2 Vista onwards and should be preferred where possible. At the time, this referred to the schtasks in XP and Server 2003 which only accept the System as the parameter per the old version manual technet.microsoft.com/en-us/library/bb490996.aspxRagged
On XP you can't run scheduled task as SYSTEM. Good luck with that. This one summarize it well: cwl.cc/2011/12/run-scheduled-task-as-system.htmlUranyl
H
15

In .NET development, I normally start off by developing a Console Application, which will run will all logging output to the console window. However, this is only a Console Application when it is run with the command argument /console. When it is run without this parameter, it acts as a Windows Service, which will stay running on my own custom coded scheduled timer.

Windows Services, I my mind, are normally used to manage other applications, rather than be a long running application. OR .. they are continuously-running heavyweight applications like SQL Server, BizTalk, RPC Connections, IIS (even though IIS technically offloads work to other processes).

Personally, I favour scheduled tasks over Window Services for repititive maintenance tasks and applications such as file copying/synchronisations, bulk email sending, deletion or archiving of files, data correction (when other workarounds are not available).

For one project I have been involved in the development of 8 or 9 Windows Services, but these sit around in memory, idle, eating 20MB or more memory per instance. Scheduled tasks will do their business, and release the memory immediately.

Horsy answered 22/11, 2011 at 9:2 Comment(1)
Frankly, this is one of few answers that make a sense to me but I think windows services will better in the case of a job starts every two minutes because starting the process and put it in memory and then remove it will consume a lot of resources. It is better to sacrifice 20 MBs of memory in this case.Vaginismus
V
13

What's the overhead of starting and quitting the app? Every two minutes is pretty often. A service would probably let the system run more smoothly than executing your application so frequently.

Both solutions can run the program when user isn't logged in, so no difference there. Writing a service is somewhat more involved than a regular desktop app, though - you may need a separate GUI client that will communicate with the service app via TCP/IP, named pipes, etc.

From a user's POV, I wonder which is easier to control. Both services and scheduled tasks are pretty much out of reach for most non-technical users, i.e. they won't even realize they exist and can be configured / stopped / rescheduled and so on.

Valparaiso answered 23/12, 2008 at 23:3 Comment(0)
C
11

The word 'serv'ice shares something in common with 'serv'er. It is expected to always be running, and 'serv'e. A task is a task.

Role play. If I'm another operating system, application, or device and I call a service, I expect it to be running and I expect a response. If I (os, app, dev) just need to execute an isolated task, then I will execute a task, but if I expect to communicate, possibly two way communication, I want a service. This has to do with the most effective way for two things to communicate, or a single thing that wants to execute a single task.

Then there's the scheduling aspect. If you want something to run at a specific time, schedule. If you don't know when you're going to need it, or need it "on the fly", service.

My response is more philosophical in nature because this is very similar to how humans interact and work with another. The more we understand the art of communication, and "entities" understand their role, the easier this decision becomes.

All philosophy aside, when you are "rapidly prototyping", as my IT Dept often does, you do whatever you have to in order to make ends meet. Once the prototyping and proof of concept stuff is out of the way, usually in the early planning and discovering, you have to decide what's more reliable for long term sustainability.

OK, so in conclusion, it's highly dependent on a lot of factors, but hopefully this has provided insight instead of confusion.

Cornea answered 1/8, 2013 at 12:44 Comment(0)
C
4

A Windows service doesn't need to have anyone logged in, and Windows has facilities for stopping, starting, and logging the service results.

A scheduled task doesn't require you to learn how to write a Windows service.

Chivalric answered 23/12, 2008 at 23:2 Comment(2)
Scheduled tasks can also run without the user being logged in, but the user's password must be provided to the scheduling agent.Earing
@moodforaday Unless the account has no configured passed (e.g. NT AUTHORITY\LocalService, or NT AUTHORITY\NetworkService). Any supplied password is ignored because the accounts have no password.Dissatisfaction
R
4
  1. It's easier to set up and lock down windows services with the correct permissions.
  2. Services are more "visible" meaning that everyone (ie: techs) knows where to look.
Rasia answered 23/12, 2008 at 23:5 Comment(6)
Your first point also applies to scheduled tasks. I'm not sure what "more visible" means. Scheduled tasks can be viewed just as easy as services.Alethaalethea
@w4g3n3r: Most tech people know how to look at windows services to see what is running. Further, if it's a service (and running) it will show up in the normal Task Manager list. Very Very few people ever use scheduled tasks.Rasia
Further, techs know to look in the event viewer when there is a problem. Scheduled tasks store that information in a log file on the file system. I'm willing to bet most people wouldn't even know where to look for that.Rasia
I would disagree about "Very Very few people ever use scheduled tasks" unless you have statistics. I see them all the time. For non-coders that need to run something every 2 min, they just navigate to Scheduled Tasks (same difficulty as getting to Services), but to create a new one there is a Wizard. So all they have to know is where the program or script is and how often it should run. Now, if you know how to code, and have the machine on a network, need to protect the login, need built-in handling to prevent multiple instances (if one runs over 2 minutes) then I'd go with a service.Joyjoya
"Most tech people know how to look at windows services to see what is running". That's one of the problems with services; they run all the time - consuming user and kernel resources simply for the bookeeping of a running process. That's why Microsoft merged as many services into single process as possible (svchost.exe); to remove needless resource consumption simply by having processes.Dissatisfaction
@IanBoyd: I'd argue that the merging into svchost has caused a large number of problems for techs trying to identify exactly what's going on.Rasia
V
3

This is an old question but I will like to share what I have faced.

Recently I was given a requirement to capture the screenshot of a radar (from a Meteorological website) and save it in the server every 10 minutes.

This required me to use WebBrowser. I usually make windows services so I decided to make this one service too but it would keep crashing. This is what I saw in Event Viewer Faulting module path: C:\Windows\system32\MSHTML.dll

Since the task was urgent and I had very less time to research and experiment, I decided to use a simple console application and triggered it as a task and it executed smoothly.

I really liked the article by Jon Galloway recommended in accepted answer by Mark Ransom.

Recently passwords on the servers were changed without acknowledging me and all the services failed to execute since they could not logon. So ppl claiming in the article comments that this is a problem. I think windows services can face same problem (Pls. correct me if I am wrong, I am jus a newbie)

Also the thing mentioned, if using task scheduler windows pop up or the console window pops up. I have never faced that. It may pop up but it is at least very instantaneous.

Volcano answered 23/7, 2016 at 22:31 Comment(1)
I thought Jon Galloway's article made some good points. Also, for the complaint about scheduled tasks failing to execute due to a password change or whatever, it is possible to respond a scheduled task failing to run, so you can notify users or whatever you would like to do. See solution here: superuser.com/questions/249103/…Bierman
U
2

Why not provide both?

In the past I've put the 'core' bits in a library and wrapped a call to Whatever.GoGoGo() in both a service as well as a console app.

With something you're firing off every two minutes the odds are decent it's not doing much (e.g. just a "ping" type function). The wrappers shouldn't have to contain much more than a single method call and some logging.

Ushijima answered 23/12, 2008 at 23:51 Comment(0)
T
1

Generally, the core message is and should be that the code itself must be executable from each and every "trigger/client". So it should not be rocket science to switch from one to the other approach.

In the past we used more or less always Windows Services but since also more and more of our customers switch to Azure step by step and the swap from a Console App (deployed as a Scheduled Task) to a WebJob in Azure is much easier than from a Windows Service, we focus on Scheduled Tasks for now. If we run into limitations, we just ramp up the Windows Service project and call the same logic from there (as long as customers are working OnPrem..) :)

BR, y

Trinitarianism answered 18/3, 2019 at 15:8 Comment(0)
H
0

Windows services want more patience until it's done. It has a bit hard debug and install. It's faceless. If you need a task which must be done in every second, minute or hour, you should choice Windows Service.

Scheduled Task is quickly developed and has a face. If you need a daily or weekly task, you can use Scheduled Task.

Howdah answered 17/10, 2017 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.