Windows service scheduled execution


If I have a Windows Service that needs to execute a task every 30 seconds which is better to use; the Timer() class or a loop that executes the task then sleeps for a number of seconds?

class MessageReceiver { public MessageReceiver() { } public void CommencePolling() { while (true) { try { this.ExecuteTask(); System.Threading.Thread.Sleep(30000); } catch (Exception) { // log the exception } } } public void ExecutedTask() { // do stuff } } class MessageReceiver { public MessageReceiver() { } public void CommencePolling() { var timer = new Timer() { AutoReset = true, Interval = 30000, Enabled = true }; timer.Elapsed += Timer_Tick; } public void Timer_Tick(object sender, ElapsedEventArgs args) { try { // do stuff } catch (Exception) { // log the exception } } }

The windows service will create an instance of the MessageReciever class and execute the CommencePolling method on a new thread.


I think it really depends on your requirement.

<strong>case 1.</strong> Suppose you want to run this.ExecuteTask() every five minutes starting from 12:00AM (i.e., 12:00, 12:05, ...) and suppose the execution time of this.ExecuteTask() varies (for example, from 30 sec to 2 min), maybe using timer instead of Thread.Sleep() seems to be an easier way of doing it (at least for me).

However, you can achieve this behavior with Thread.Sleep() as well by calculating the offset while taking timestamps on a thread wake-up and on a completion of this.ExecuteTask().

<strong>case 2.</strong> Suppose you want to perform the task in the next 5 min just after completion of this.ExecuteTask(), using Thread.Sleep() seems to be easier. Again, you can achieve this behavior with a timer as well by reseting the timer every time while calculating offsets on every time this.ExecuteTask() completes.

<strong>Note1</strong>, for the case 1, you should be very careful in the following scenario: what if this.ExecuteTask() sometimes takes more than the period (i.e. it starts at 12:05 and completes 12:13 in the example above).


What does this mean to your application and how will it be handled?

a. Total failure - abort the service or abort the current(12:05) execution at 12:10 and launch 12:10 execution.<br /> b. Not a big deal (skip 12:10 one and run this.ExecuteTask() at 12:15).

c. Not a big deal, but need to launch 12:10 execution immediately after 12:05 task finishes (what if it keeps taking more than 5 min??).

d. Need to launch 12:10 execution even though 12:05 execution is currently running.

e. anything else?

</li> <li>

For the policy you select above, does your choice of implementation (either timer or Thread.Sleep()) easy to support your policy?

</li> </ol>

<strong>Note2</strong>. There are several timers you can use in .NET. Please see the following document (even though it's bit aged, but it seems to be a good start): <a href="http://msdn.microsoft.com/en-us/magazine/cc164015.aspx" rel="nofollow">Comparing the Timer Classes in the .NET Framework Class Library</a>


Are you doing anything else during that ten second wait? Using Thread.sleep would block, preventing you from doing other things. From a performance point of view I don't think you'd see too much difference, but I would avoid using Thread.sleep myself.

There are three timers to choose from - System.Windows.Forms.Timer is implemented on the main thread whereas System.Timers.Timer and System.Threading.Timer are creating seperate threads.


I believe both methods are equivalent. There will be a thread either way: either because you create one, or because the library implementing the Timer class creates one.

Using the Timer class might be slightly more less expensive resource-wise, since the thread implementing timers probably monitors other timeouts as well.


I this the answers to <a href="https://stackoverflow.com/questions/246697/windows-service-and-timer" rel="nofollow">this question</a> will help.


Not answered by me but John Saunders (above)... the answer can be found here <a href="https://stackoverflow.com/questions/1099516/for-a-windows-service-which-is-better-a-wait-spin-or-a-timer" rel="nofollow">For a windows service, which is better, a wait-spin or a timer?</a>


  • format of ByteArray returned from C is invalid
  • Use tornado future to fetch url, two different ways get different results
  • Issue binding to ListBox WP7
  • Multiple Rows for same identifier
  • audio controll - backward , forward buttons - Java script
  • How can I import an ANTLR lexer grammar into another grammar using Gradle 2.10?
  • How can I pull data (JSON) from a clicked ng-repeat item to load a new, item specific page using $st
  • ApacheConnectorProvider : Jersey Client 2.5.1
  • phonegap: is it possible to detect double touch swipe from Javascript?
  • Proper Form of API request to Blogger using Java/App Engine -error 401
  • Retrieving saved checkboxes' name and values from database
  • How to concatenate data.frame inside lists by using names?
  • Parsing a complicated array with GetJSON Jquery
  • Using Facebook Graph API with ASP.NET
  • Mask Image to Video Frame similar as MV Master
  • configure openjpa on to spring boot
  • Hyperlink to Outlook Attachment
  • Python tk scrollbar becomes inactive once text is outside the screen
  • getting the values of checkboxes in a checkboxlist control
  • What's the difference between using RDFS/OWL and XML?
  • Handle query parameters recursively using htaccess
  • How to add ng-app after page load?
  • connect.cookieParser and connect.session
  • jQuery - Prevent activation on first click
  • SELECT on JSONField with Django
  • Creating Dictionaries from Lists inside of Dictionaries
  • internal javascript not works in angular2
  • Circular Left Rotation Algorithm in C#
  • How to display content depending on dropdown menue user selection
  • How to resolve this in PHPUnit where it is asking me to set KERNEL_DIR in my phpunit.xml?
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • Add font awesome icon to custom add to cart button in Woocommerce 3
  • how to read to huge file into buffer
  • Ruby regex for matching simpliest Ruby's regexes
  • JQuery: Infinite input select
  • How to integrate angular2-material (alpha 8.2) with angular2-Quickstart app
  • How to handle div that is created dynamically in a table
  • Bind selectedDates Aggregation for Calendar
  • Google App Engine backend servlet not responding
  • Call Microservice from another Microservice within Docker