Wednesday 8 April 2015

MVC running Background service without creating any scheduler.exe (inspired from stackoverflow's idea)

In Global.asax      

    public class MvcApplication : System.Web.HttpApplication
    {
        private const string DummyCacheItemKey = "BackgroundService";
        private static string DummyPageUrl = "localhost/dummy";// any other valid url


        protected void Application_Start()
        {  // other code snippets

           ...................................
           ...................................
           RegisterCacheEntry();
        }


                   protected void Application_BeginRequest(object sender, EventArgs e)
        {  // other code snippets

           ....................................
           ....................................
           if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
            {
                // Add the item in cache and when succesful, do the work.
                RegisterCacheEntry();
            }
        }

        private bool RegisterCacheEntry()
        {
            if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return false;

            HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null,
                DateTime.MaxValue, TimeSpan.FromMinutes(1),
                CacheItemPriority.Normal,
                new CacheItemRemovedCallback(CacheItemRemovedCallback));

            return true;
        }

        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            // Do the service works
            new Thread(() =>
            {
                try
                {
                    BackgroundServices.DoWork();
                }
                catch (Exception ex)
                {
                    //log the exception
                }
            }).Start();

            BackgroundServices.HitPage();
        } 

     }

Create BackgroundServices class as follows

    public class BackgroundServices
    {
        private static readonly string DummyPageUrl ;

        static BackgroundServices()
        {
            DummyPageUrl = "localhost/dummy";// any other valid url        }       

        public static void HitPage()
        {
            WebClient client = new WebClient();
            client.DownloadData(DummyPageUrl);
        }

        public static void DoWork()
        {
            try
            {
                using (SqlConnection con = new SqlConnection("connectionstring"))
                {
                    con.Open();
                    // database related work
                    con.Close();
                }
            }catch(Exception ex)
            {
                //logging the exception
            }
        }
    }


Now create a dummy action in any controller and map the route of the same in RouteConfig.cs and set the "DummyPageUrl" to that url.

No comments:

Post a Comment