2

Background is the following: A Windows Service which is supposed to perform an action once per day at a given time.

I have currently implemented this by creating a timer and added the ElapsedEventHandler. The event fires every t minutes and it is then checked that we are passed the configured time. If so the action is performed and if not nothing happens.

A colleague asked me if it was not easier just to have a while(true) loop containing a sleep() and then of course the same logic for checking if we are past the time for action.

Question: Can one say anything about the "robustness" of an event vs. a while(loop)? I am thinking of the situation where the thread "dies" so the while(true) loop exits. Is this more "likely" to happen in the one scenario vs. the other?

Karsten Strøbæk
  • 643
  • 2
  • 8
  • 17
  • Is the service doing anything else, or is it solely there to run once per day? In any case, feel free to also look at my question: http://stackoverflow.com/questions/481760/ – Michael Stum Oct 03 '11 at 05:52
  • It is idle when not performing the action, hence idle most of the day. As perposed by selbie, I will check out the Task Scheduler. Thank you. – Karsten Strøbæk Oct 03 '11 at 06:15

2 Answers2

8

I'd vote for neither.

If your service just sits idle for an entire day periodically waking up (and paging code in) to see if "it's time to run", then this is a task better suited for the Windows Task Scheduler. You can programatically install a task to run every day through the task scheduler. Then your code doesn't need to be running at all unless it's time to run. (Or if your service does need to run in the background anyway, the task in the scheduler can signal your service to wake up instead of timer logic).

selbie
  • 100,020
  • 15
  • 103
  • 173
0

Both will be equally robust if you use proper error handling.
If you don't use proper error handling they will be equally brittle.

while(true)
{
   ...
   Thread.Sleep(1000);
}

will make your service slow when responding to the standard service events like OnStop.

Besides, where do you put your while loop? In a separate thread? You will get more manual management if you use a loop too.

To summarize: use a timer.

Albin Sunnanbo
  • 46,430
  • 8
  • 69
  • 108