Search code examples
c#.netwindows-services

Creating windows service without using timer control


I am creating windows service, whatever the article I am going through they are using System.Timers.Timer, without mentioning that why they are using it.

Is it mandatory to use Timer?

These below urls are using Timer with windows service

https://www.c-sharpcorner.com/UploadFile/8a67c0/create-and-install-windows-service-step-by-step-in-C-Sharp/

https://www.c-sharpcorner.com/article/create-windows-services-in-c-sharp/

https://dzone.com/articles/create-windows-services-in-c

https://www.aspsnippets.com/Articles/Tutorial-to-create-a-simple-Windows-Service-with-sample-example-in-C-and-VBNet.aspx

Can't it be done just by writing code in these methods

protected override void OnStart(string[] args)
{
    base.OnStart(args);
    GetFailedProductDetails();
}

protected override void OnStop()
{
    base.OnStop();
}

Edit:

Logic to execute service every 30 mins

<appSettings>
<add key ="Mode" value ="Interval"/>
<add key ="IntervalMinutes" value ="30"/>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>

My goal:

I want to run this service every 30 mins to execute GetFailedProductDetails() method. For that I have written code in App.config file.


Solution

  • A service does not repeat. It simply starts once, and then runs as long as it is not stopped. If it needs to do repeated tasks, you need to take care of the repeating yourself, in your code.

    Of course, you could set up an ugly system with an endless for-loop and a Thread.Sleep(), but the issue there is, when starting a service, Windows expects the OnStart to finish, so it can conclude that the service is started, rather than still starting up. The OnStart function should prepare everything to make the service operations run, but it should not execute these operations itself.

    So, the reason the timer is used for that is so the OnStart function can finish correctly, and then after that, periodically, the service operations, in your case the GetFailedProductDetails() function, can be started by the timer.


    As for that piece of config, as I said in my comment, a bit of xml is not code. The guide you copied that from has explicitly written programming to read, interpret and apply these settings, to set up a Timer object to make it repeat in the configured intervals. Copying that xml without copying the accompanying code will do nothing to help you.

    You can use the config file to set up the interval settings, of course, but then you'll also have to actually write the code to read them. The concept of a repeating service doesn't need such settings, though. You can perfectly program the service with a hardcoded half-hour interval and leave it at that.