Tuesday, October 30, 2012

Using a Windows Service as a Timer

BACKGROUND: Recently, I came across an issue with an MVC application I was developing. This application is composed of two sections: the Frontend and Backend. The Frontend contains all the visuals (what the user sees) and requests information from the Backend. The Backend fetches all the data from the database and sent it to the Frontend.

ISSUE: The communication between the Frontend and the Backend was being lost randomly. I was never able to witness it. We only knew it happened because the Frontend would display, but no data would be present.

RESOLUTION: I am going to create a windows service that is going to run on the machine hosting the Frontend project. This service will start a timer that will tick every x minutes (5 minutes for this application). On every tick, the Frontend will send a request to the Backend. If the request does NOT return "true" from the Backend, an error will be written to the log.

STEPS: *Using Visual Studio 2010 in .NET v.4

Step 1: Create a basic Windows Service Project and Setup Project
  • http://msdn.microsoft.com/en-us/library/aa984464(v=vs.71).aspx
  • You can ignore the OnContinue() action
  • Tip - For step 7 under the section 'To create the installers for your service', I chose to use Local System instead of Local Service. Local Service was NOT working for me. I would get a permissions error when I attempted to start the service and it would not start.
Step 2: Install the service, Start the service and Verify that it is running by checking the log in the Event Viewer

Step 3: Uninstall the service

Step 4: Add the Timer to the Windows Service
  • Add private System.Timers.Timer _timer = new System.Timers.Timer() to the top of the class
  • Call SetupTimer() from the OnStart function
private void SetupTimer(){
   int interval = 300000; //default to 5 minutes
   this._timer.Interval = interval;
   this._timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
   this._timer.Start();
}
  • Create another function called TimerElapsed() in the same file
 
void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e){
   eventLog1.WriteEntry("Communication check...");
   //Connect to a Backend function that returns true
   if (response)
     //Do nothing or write to log "success"
   else
     eventLog1.WriteEntry("Communication to Backend Failed",EventLogEntryType.Error);
     //EventLogEntryType.Error makes the entry get marked as an error in the Event Log
}

Step 5: Build the Windows Service Project

Step 6: Build the Setup Project
  • Be sure the build these projects in the proper order!
Step 7: Install the service, Start the service and Verify that it is running by checking the log in the Event Viewer


For more information, visit our site: www.rippe.com/index.htm

No comments:

Post a Comment