ScubaSteve
ScubaSteve

Reputation: 8270

How do I stop a Windows Service when it has completed?

So, I have a windows service that will be started up once an hour. It will query some database tables and put data in other tables. After this is done, I would like to stop the service, that way, an hour later, it can be started again. I have tried:

this.Stop();

and

Service = new ServiceController(GlobalConstants.WindowsServiceName);
Service.Stop();
            Service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 5, 0));

When I do the first, it runs, but I get an alert that it unexpectedly stopped. There are no errors in the Event Viewer. Everything went well, it just leaves a scary alert.

When I do the second, it stalls out and says it could not start the service and hit the timeout.

If I do not have any stop and just wait for the program, the service remains in the Started state.

GOAL

To stop the service without any warning type alerts or messages. It would be nice if the OnStop() was called as well.

Upvotes: 2

Views: 2732

Answers (1)

Habib
Habib

Reputation: 223422

You don't have to start and stop the service. Use a Timer. Set its interval to one hour and execute your process in timer elapsed event.

Define a class level Timer object. Instantiate it in OnStart and enable it. In the Elapsed event execute your process, something like:

private System.Timers.Timer serviceTimer;
protected override void OnStart(string[] args)
{
    serviceTimer = new System.Timers.Timer();
    serviceTimer.Interval = 3600000; //one hour
    serviceTimer.Elapsed += serviceTimer_Elapsed;
    serviceTimer.Enabled = true;
}

void serviceTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    serviceTimer.Enabled = false;
    // do your process
    serviceTimer.Enabled = true;
}

You can also use System.Threading.Timer, where you can specify the timer to start immediately and then execute every one hour like:

System.Threading.Timer timer = new System.Threading.Timer(
       new TimerCallback(YourMethod), 
       null, 
       0,  //initial start time
       3600000);

Upvotes: 3

Related Questions