Monday, August 18, 2014

Simple Task Scheduling in asp.net website in Global.asax file

Global.asax.cs

private static DateTime taskLastRun;

void Application_Start(object sender, EventArgs e)
{
    taskLastRun= DateTime.Now;
}
 
void Session_Start(object sender, EventArgs e)
{
  DoTask();
}

/*Private method implemented in Global.asax file.
* Example Task to run every time application runs
* In this, it will delete the one day old files stored in uploads directory. 
*/

static void DoTask()
{
  var aDayAgo = DateTime.Now.AddDays(-1);
  if (taskLastRun.IsGreaterThan(aDayAgo))
  {
    var path = HttpContext.Current.Server.MapPath("Uploads");
    var folder = new DirectoryInfo(path);
    FileInfo[] files = folder.GetFiles();
    foreach (var file in files)
    {
      if(file.CreationTime.IsOlderThan(aDayAgo))
      {
        File.Delete(path + file.Name);
      }
    }
    taskLastRun= DateTime.Now;
  }
}
 
//Extension method to compare two dates 
public static bool IsGreaterThan(this DateTime dt1, DateTime dt2)
{
  return dt1 < dt2;
} 

No comments:

Post a Comment