Wednesday, May 30, 2012

Scheduled Tasks in ASP.NET Web Applications using Timers

I'm just found a article that I found on the MSDN blog. And I've just decieded to share on my blog with more explantation.

Before I found this, I honestly had known that the scheduled tasks can be only running on window scheduler tasks.

I had even tried to use Threading with looping to avoid window scheduler tasks on my web application.

Finally, I just found this article .

Scenario: A Web app calls wcf services every one minute. As I'm MVC web developer, my web app is always MVC application. System timer In global.asax, you need to create a Timers method. In below example, I give timer method name to ServiceTimers.

   1:  private void ServiceTimers()
   2:  {
   3:       System.Timers.Timer serivceTimer = new System.Timers.Timer();
   4:       serivceTimer.Enabled = true;
   5:       serivceTimer.Interval = (60000); // one minute
   6:   
   7:       serivceTimer.Elapsed += new
   8:       System.Timers.ElapsedEventHandler(ServiceTimer_Elaspsed);
   9:  }

Within the method, the last line is obviously event handler which call to a event which contains Web service called.

   1:  protected void ServiceTimer_Elaspsed(object sender, System.Timers.ElapsedEventArgs e)
   2:  {
   3:       WorkLoadClient workLoadClient = new WorkLoadClient();
   4:       workLoadClient.DoWork();
   5:  }

All together will be as below in Global.asax

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.Mvc;
   6:  using System.Web.Routing;
   7:  using NotificationService.Web.ServiceReference2;
   8:   
   9:  namespace NotificationService.Web
  10:  {
  11:      // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
  12:      // visit http://go.microsoft.com/?LinkId=9394801
  13:   
  14:      public class MvcApplication : System.Web.HttpApplication
  15:      {
  16:          public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  17:          {
  18:              filters.Add(new HandleErrorAttribute());
  19:          }
  20:   
  21:          public static void RegisterRoutes(RouteCollection routes)
  22:          {
  23:              routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  24:   
  25:              routes.MapRoute(
  26:                  "Default", // Route name
  27:                  "{controller}/{action}/{id}", // URL with parameters
  28:                  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
  29:              );
  30:   
  31:          }
  32:   
  33:          protected void Application_Start()
  34:          {
  35:              AreaRegistration.RegisterAllAreas();
  36:   
  37:              RegisterGlobalFilters(GlobalFilters.Filters);
  38:              RegisterRoutes(RouteTable.Routes);
  39:   
  40:              ServiceTimers();
  41:          }
  42:   
  43:          private void ServiceTimers()
  44:          {
  45:              System.Timers.Timer serivceTimer = new System.Timers.Timer();
  46:              serivceTimer.Enabled = true;
  47:              serivceTimer.Interval = (60000); // one minute
  48:   
  49:              serivceTimer.Elapsed += new
  50:                  System.Timers.ElapsedEventHandler(ServiceTimer_Elaspsed);
  51:          }
  52:   
  53:          protected void ServiceTimer_Elaspsed(object sender, System.Timers.ElapsedEventArgs e)
  54:          {
  55:              WorkLoadClient workLoadClient = new WorkLoadClient();
  56:              workLoadClient.DoWork();
  57:          }
  58:      }
  59:  }

And I have a WCF service project which referenced by Web app.

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Runtime.Serialization;
   5:  using System.ServiceModel;
   6:  using System.Text;
   7:  using System.Threading;
   8:  using System.Net.Mail;
   9:  using System.Net;
  10:   
  11:  namespace NotificationService.Wcf
  12:  {
  13:     
  14:      public class WorkLoad : IWorkLoad
  15:      {       
  16:          public void DoWork()
  17:          {            
  18:              var client = new SmtpClient("smtp.gmail.com", 587)
  19:              {
  20:                  Credentials = new NetworkCredential("xxxx@gmail.com", "xxxxxx"),
  21:                  EnableSsl = true
  22:              };
  23:   
  24:              client.Send("xxx@gmail.com", "xxxx@email.com", "test", "testbody");
  25:            
  26:          }
  27:          
  28:      }
  29:  }
reference:http://weblogs.asp.net/samirgeorge/archive/2009/05/09/scheduled-task-in-asp-net-web-application-using-timers.aspx

1 comment:

Andrew Stevenson said...

Should it required to application start every time?

Dot NET Experts