views:

51

answers:

3

Scenario

I have a C# Windows Service that essentially subscribes to some events and if anything is triggered by the events, it carries out a few tasks.

The Thing...

....is that these events are monitoring processes, which I need to restart at certain times of the day.

Question

What's the best way I can go about performing this task at an exact time?

Thoughts so far are:

1)To use a timer that checks what time it is every few minutes. 2)Something that isn't a timer and doesn't suck as an implementation.

Help greatly appreciated.

A: 

You could set off timers that run at particular times of the day but I would probably favour the following approach.

while (!closing)
{
if (SomethingNeedsDoingNow()) { DoIt(); }

Thread.Sleep(1);
}

This will barely consume any resources and will then be able to fire off events at any time of the day to a 1 second granularity easily.

Note SomethingNeedsDoingNow should check the current time, and see if any events need firing. If you can get away with a looser granularity then you can sleep for 60seconds instead.

Chris
A: 

One option, if you really want to avoid implementing a timer, is a windows scheduled task that kills your processed when it's fired.

You can then have your service constantly polling to make sure the processes are running, and if not start them.

Still kind of 'timer-y' granted, but it's another approach.

Ian Jacobs
A: 

Start a new thread at service start with IsBackground = true. This ensures your thread dies when your service stops, so you can simply start and forget it.

In the thread, use an endless loop with Thread.Sleep(60*1000)'s, waiting for the correct time of day to do the restart. The restart should probably be done on a new thread with IsBackground = false to prevent your service from stopping before your app is finished restarting (restricted to 30 secs or so permitted by Windows for your service to shut down). Alternatively you can spawn a separate process for the restart operation.

Dag