Application Timers (to replace scheduled tasks)

I do not like scheduled tasks.
They most often take the form of little bits of unversioned code (in console apps) that exist outside the main solution.
Moving these into the main application allows us to utilise the application’s logging utilities, adds versioning to the logic and configuration settings and ensures that the code is both updated and deployed along with the rest of the solution.

Below is some initial code – the idea is to have a singleton class that starts a set of timers. This can then be called from Application_Start or a similar global event.
Some improvements to the below would be to make the application timers use the provider pattern – so we can code up new timers when we need, and perhaps add a .config section to load these from.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Timers;
using System.Net;
using HobNobClubServices.Library;
 
namespace HobNobClubApps.Library
{
      /// 
      /// Singleton timer
      /// 
      public sealed class ApplicationTimers
      {
            private static readonly ApplicationTimers instance = new ApplicationTimers();
            private static bool timersInitialised = false;
 
            private ApplicationTimers() { }
 
            public static ApplicationTimers Instance
            {
                  get
                  {
                        return instance;
                  }
            }
 
            public void InitTimers()
            {
                  if (timersInitialised)
                        return;
 
                  InitHobNobInsuranceEmailAbandonedQuotesTimer();
 
                  timersInitialised = true;//Only do this once in the application:
            }
 
            private void InitHobNobInsuranceEmailAbandonedQuotesTimer()
            {                
                  Timer HobNobInsuranceEmailAbandonedQuotesTimer = new Timer();
                  int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                  HobNobInsuranceEmailAbandonedQuotesTimer.Interval = (intervalInMinutes * 60000); //Convert to millisecs
                  HobNobInsuranceEmailAbandonedQuotesTimer.Elapsed += new ElapsedEventHandler(HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed);
                  HobNobInsuranceEmailAbandonedQuotesTimer.Start();
            }
 
            private void HobNobInsuranceEmailAbandonedQuotesTimer_Elapsed(object sender, ElapsedEventArgs e)
            {
                  string errorMsg = String.Empty;
                  try
                  {
                        int intervalInMinutes = Properties.Settings.Default.HobNobInsuranceEmailAbandonedQuotesTimerInterval;
                        //Set the delay in emailing people to the same as this timer interval (so if this timer runs every 30 mins, people will be emailed if they've left a quote alone for 30 mins):
                        string methodNameAndParams = String.Format("/EmailAbandonedQuickQuotes?delayInMinutes={0}", intervalInMinutes);
                        WebRequest webRequest = HttpWebRequest.Create(Properties.Settings.Default.HobNobClubApps_SLHobNobInsurance_HobNobInsurance + methodNameAndParams);
                        WebResponse webResponse = webRequest.GetResponse();                    
                  }
                  catch (Exception ex)
                  {
                        errorMsg = ex.Message;
                        ExceptionManager.LogExceptionEvent(ex, Logger.Source.HobNobInsurance);
                  }
 
                  Logger.WriteInfoLog(
                        String.Format("The HobNobInsuranceEmailAbandonedQuotesTimer ran at {0} {1}",
                                                DateTime.Now, String.IsNullOrEmpty(errorMsg) ? "with no errors (from the timer)." : "and failed with: " + errorMsg),
                              Logger.Source.HobNobInsurance);
            }
      }
}
 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: