Invoke Methods in ASP.Net Automatically Over a Fixed Period of Time

The Prologue

Often there are times when you need a task to be executed automatically, after a fixed period of time, similar to JOBS in SQL Server. Even though implementing JOBS in SQL Server isn't as tough as nails but they won't be helpful if the functionality of JOBS are to be implement ASP.NET. So, here is a short and crispy implementation that would definitely help you implement the functionality of performing a series of code on a daily basis or after a fixed interval of time. For example, sending emails to the customers whose subscription will soon expire, or an application that reminds you of a specific task after every 2 or 3 days.

The implementation is not an issue but before starting the implementation what we need is a utility that would run indefinitely and that will help us invoke the method that needs to be executed automatically. Unfortunately there is no such utility in ASP.NET that would help us in getting the desired behaviour so the only option here is to catch hold of a simple but a good work around. Normally the operations done on an ASP page is a reflex to an action like "Click of a Button" or "Loading of a Page", so these won't be of any help since the functionality that needs to be implemented is to receive a reflex action without any input action. So we need something that would provide us an output without any input.

Something like a Cache item can be helpful in this case and a call-back from this item can easily be received.

The Implementation

All the operation that we need to apply on the cache item will be implemented in the Global.asax of the ASP.NET application.

The ASP worker process checks the cache item every once in a while. So the first thing we need to do is register a cache item and set the duration for expiry of the call-back.

  1. private const string SampleCacheKey = "CacheItem";  
  3. protected void Application_Start(Object sender, EventArgs e)  
  4. {  
  5.    RegisterCacheItem();  
  6. }  
  8. private bool RegisterCacheItem ()  
  9. {  
  10.    ifnull != HttpContext.Current.Cache[SampleCacheKey] ) return false;  
  12.    HttpContext.Current.Cache.Add(SampleCacheKey, "Test"null,  
  13.    DateTime.MaxValue, TimeSpan.FromMinutes(10),  
  14.    CacheItemPriority.Normal,  
  15.    new CacheItemCallback( CacheItemCallback ) );  
  17.    return true;  
  18. }  
This sample cache item will get us a call-back and that is all we require. And in this call back we will perform our task that needs to be invoked automatically over a period of time. But with this call back the cache item will be removed, so what we need here is to create and store another cache item at this point so as to receive further call-backs. To do this we can invoke a call to any xyz website with the WebClient class. When the xyz website is being executed, there we can register the cache item can be by getting the HttpContext.
  1. public void CacheItemCallback( string key,  
  2. object value, CacheItemRemoved remove)  
  3. {  
  4.    CallWebsite();  
  5.    PerformTask();  
  6. }  
The "PerformTask" method will implement the functionality that needs to be invoked automatically, whereas the "CallWebsite" method will call a website to create another cache item once the previous one is trashed.
  1. private const string website =  
  2. "http://localhost/SendEmail.aspx";  
  4. private void CallWebsite ()  
  5. {  
  6.    WebClient client = new WebClient();  
  7.    client.DownloadData(website);  
  8. }  
We would also need to check if that if the request is made from the called website and only then proceed forward. This can be done in the "Application_BeginRequest" of the Global class.
  1. protected void Application_BeginRequest(Object sender, EventArgs e)  
  2. {  
  3.    //Register another item  
  5.    if( HttpContext.Current.Request.Url.ToString() == website)  
  6.    {  
  7.       // Add item  
  9.       RegisterCacheItem();  
  10.    }  
  11. }  
Perform the Task (send email):
  1. private void PerformTask()  
  2. {  
  3.    MailMessage message = new MailMessage();  
  5.    message.To.Add(new MailAddress([email protected]));  
  6.    message.Subject = "Test Mail";  
  7.    message.Body = "This is a Test Mail";  
  8.    message.From = new MailAddress("[email protected]");  
  9.    SmtpClient mclient = new SmtpClient();  
  10.    mclient.Host = "";  
  11.    mclient.Port = 587;  
  12.    mclient.EnableSsl = true;  
  13.    mclient.Credentials = new System.Net.NetworkCredential("[email protected] ""test@123");  
  14.    mclient.Send(message);  
  15. }  
The Aftermath

Congrats! You have successfully implemented the functionality to invoke a method automatically over a fixed period of time. This implementation is one of the easiest methods to perform scheduled tasks would also stand by you even when the WebPage is not running, but provided it is hosted.