Link to home
Start Free TrialLog in
Avatar of ersldublin
ersldublin

asked on

Using TimerCallback to periodically start a function in a Windows Service

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.

ASKER CERTIFIED SOLUTION
Avatar of gregoryyoung
gregoryyoung
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
or use a System.Timer and disable it upon entry to the interrupt handler and re-enable just before exiting the handler.