We help IT Professionals succeed at work.

Using TimerCallback to periodically start a function in a Windows Service

Last Modified: 2013-12-17
I have a WIndows Service developed in C#.  A function called "ProcessRoutine" is kicked off periodically (at say, 1 or 2 minute intervals).  This function polls a database table for new records, and if new records exist, some processing is initiated (such as File copies across a network, various database inserts, updates etc...).  The length of time this processing takes varies hugely.... I have noticed that it can be anything from a few seconds to a few minutes, sometimes as much as 30 minutes (due to copying large files).

I am kicking off the "ProcessRoutine" function using the following approach within my "OnStart" method:

      // Create the delegate that invokes methods for the timer.
                 TimerCallback timerDelegate = new TimerCallback (this.ProcessRoutine);
                AutoResetEvent autoEvent = new AutoResetEvent(false);                  
                processTimer = new System.Threading.Timer(timerDelegate, autoEvent, 1000, settingsFile.TimerInterval);

... where "settingsFile.TimerInterval" is a milliseconds value, usually being 1 minute.  This is the preferred time interval for querying the database.

My question is how can I ensure that the ProcessRoutine has completed before I call it again?  
Is there a way to query a Timer to ask if it completed what was kicked off before?  
I see from the timestamps on my log entries from "ProcessRoutine" that the records are all over the place after the first time ProcessRoutine is called if there are 20 or 30 records to process.  I need to be sure that the function is not called again until it has finished the previous time.
Do I need to adopt a different approach to all this?
Should I kill the "processTimer" upon entering "ProcessRoutine" and then re-intantiate it once I am happy all the records have been processed? (probably a mad suggestion!)

Many thanks.

Watch Question

Top Expert 2004
This one is on us!
(Get your first solution completely free - no credit card required)

or use a System.Timer and disable it upon entry to the interrupt handler and re-enable just before exiting the handler.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.