Answered by:

Windows Service using Timer starting then immediately stopping

Question

I am creating a C# Windows service that extracts data once a day at a configured time.

In the service code, for the OnStart, I am setting up a timer, adding an event handler to the timer, turning off AutoReset, and calculating the timer interval based on the amount of time to the next run. I am then enabling the timer, and
Start() ing the timer. The event handler first checks for the AutoReset being off, and if it is, it resets the timer interval to 24 hours, and turns AutoReset on, then runs the data extract job. This way, after the first run, the service sets up
to run every day at the same time.

The problem I am having is that as soon as I start the service, it stops, saying that it Started then stopped, perhaps it had no work to do, etc.

Answers

You probably encountered an exception. By default, .NET does not do a good job of logging these for services.

Do both of the following:

1. To catch errors in OnStart: Wrap everything in OnStart with a try/catch of Exception. Log the error, then rethrow it.

2. To catch errors elsewhere: First thing in OnStart, add a handler for the AppDomain.CurrentDomain.UnhandledException event. In the handler log the error.

Note that if you are just starting on this service, it might be easier to build this as a console application so that it is simple to debug. Main is your OnStart. Port it into a service (which will be trivial) once you are nearly done.

All replies

You probably encountered an exception. By default, .NET does not do a good job of logging these for services.

Do both of the following:

1. To catch errors in OnStart: Wrap everything in OnStart with a try/catch of Exception. Log the error, then rethrow it.

2. To catch errors elsewhere: First thing in OnStart, add a handler for the AppDomain.CurrentDomain.UnhandledException event. In the handler log the error.

Note that if you are just starting on this service, it might be easier to build this as a console application so that it is simple to debug. Main is your OnStart. Port it into a service (which will be trivial) once you are nearly done.