Simple task Scheduling using Global asax

A frequent requirement for ASP.NET developers is to schedule tasks at regular intervals. This can include site maintenance tasks, like cleaning up old files, emailing newsletters on a schedule etc. This article examines one easy option for managing tasks like these without having to configure external tools, and discusses a couple of alternatives.

If you have access to the web server itself, you will probably use WMI to schedule tasks (http://msdn.microsoft.com/en-us/library/aa394601(VS.85).aspx) or you might even consider using Sql Server Agent to run Jobs on a schedule (http://msdn.microsoft.com/en-us/library/ms191439.aspx). But if you are using a shared hosting plan, or Sql Server Agent is not available, you need another way to manage tasks. The Global.asax file gives you access to regularly occurring events that you can use to manage this. The two main events of interest are Application_Start(), which happens when the first request to an application is made - usually as a result of the site first being deployed, or when the application process is restarted for any reason (server shutdown, recompilation etc) and Session_Start() which happens whenever a new visitor lands on your web site. See ASP.NET Application Life Cycle Overview for IIS 5.0 and 6.0 for more details.

If your web application does not feature a file called global.asax, it is easy to add one. Right click on the Project name in Solution Explorer, and choose Add New Item

From the dialogue box that appears, select Global Application Class

Your IDE should open up Global.asax as a result of this, and you should see autogenerated code within a <script runat="server"> block. Five event handlers are ready and waiting which cover Application Start, Application End, Application Error, Session Start and Session End. For the purposes of this illustration, I am going to assume that the regular task will be one that checks a folder for files that are more than one day old, and deletes them. I'm also going to assume that the web application gets enough visitors that Session_Start() will be fired often enough to serve the purpose of trigger point. We need some code that will iterate the files in a folder, and check their created date. If that date is more than 24 hours old, the file gets deleted. We don't want this code to run when every visitor lands on the site. Once a day will do. So, there needs to be some way to check when the task last ran.

At the top of the Global.asax, we will add a variable that holds a DateTime indicating when the task last ran, and initialise it to the current time when the application starts:


private static DateTime whenTaskLastRan;

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

We have decided that the task will run in Session_Start(). so we add a call to a method there:


void Session_Start(object sender, EventArgs e)
{
  DoTask();
}

At the bottom of Global.asax, we add the method DoTask() with its implementation code:


static void DoTask()
{
  var oneDayAgo = DateTime.Now.AddDays(-1);
  if (whenTaskLastRan.IsOlderThan(oneDayAgo))
  {
    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(oneDayAgo))
      {
        File.Delete(path + file.Name);
      }
    }
    whenTaskLastRan = DateTime.Now;
  }
}

A DateTime - oneDayAgo is set to 24 hours before now, or one day ago. The application variable which was set in the Application_Start() event is compared to oneDayAgo to see which is older. You might raise an eybrow at the method used to do this: IsOlderThan(). It's an extension method which looks like this:


public static bool IsOlderThan(this DateTime dt1, DateTime dt2)
{
  return dt1 < dt2;
}

In itself, it doesn't do much - it just returns a bool indicating whether one DateTime precedes another. However, its use makes the code more readable.

Alternatives

There is one alternative that I have seen for scheduling tasks without the use of third party applications, and that is the use of the Cache object. It is detailed here: http://www.codeproject.com/KB/aspnet/ASPNETService.aspx. For tasks that need to be run more often that visitors land on your site, this may be a better choice. However, it seems a little bit overkill to me. I can't think of a real world scenario where a web application really would need to execute tasks more frequently than visitors land on the site. One place where it may be useful is in performing a task at a particular time. If you need to control the time quite precisely (say with a tolerance of around 2 minutes either way) the Cache approach would be better than hoping that a visitor lands on your site at the right time. Of course ,that depends on your site and traffic levels.

Another alternative is to place the code for DoTask() in the Page_Load event of your home page. This will ensure it is run every time anyone lands on that page. In the case of my site, the home page is one of the least visited pages. You can ensure it fires for every page request by creating a BasePage which inherits from Page, and then subclass all of your web forms from BasePage. DoTask() can be placed in the Pre_Init() event of BasePage. A final option is to stick with Global.asax, and put DoTask() in Application_BeginRequest(). This will also be fired every time a page is requested on your site.

This article has looked at a number of options for automating tasks without having to configure third party tools on your web server. Which option you choose will depend on the frequency of the task, the tolerance levels you can accept in terms of timing the task, and the number of visitors your site gets.

Date Posted: Saturday, January 30, 2010 10:22 PM
Last Updated: Tuesday, November 11, 2014 8:08 AM
Posted by: Mikesdotnetting
Total Views to date: 58871

18 Comments

Sunday, January 31, 2010 12:07 AM - Jaycent Drysdale

I am building a website that relies on pulling in data from a remote rss feed and saving the feed data to my local sql server database. This needs to happen twice every hour.

the approach I have taken is to wrap a web service around the existing code that does the retrieval and update of the data.

After setting up the web service, I wrote a console app (.exe) that connects to the web service and initiate a download update cycle.

I then use windows Scheduler to call the .exe app every 3 seconds to do a download/update cycle.

Works very nicely.

Monday, February 1, 2010 4:05 AM - infocyde

Jaycent, that is the best solution for your scenario. Sometimes on shared hosting plans they don't allow you to host a console app, so you are stuck.

Monday, February 1, 2010 5:31 AM - cyril gupta

A long time ago when I had a similar requirement I spawned a separate thread using code which would remain in memory and do the performed tasks at regular intervals. It would sleep between those intervals.

It worked awesomely, but later GoDaddy started killing my threads and then I could never get this to work with GoDaddy servers.

Monday, February 1, 2010 2:18 PM - Pete

I'd take a look at using a System.Timers.Timer for performing for running your DoTask() method.

Tuesday, February 2, 2010 6:05 PM - Vasha

Guys. You are forgetting that asp.net run time will kill any threads (including the main asp.net thread) and will go idle if there were no requests for some default time. And, as was mentioned in the article, most of the hosting plans prevent you from running your exes or windows services and making them to install and manage this kind of things is not fun at all.
In the app that I'm finishing at the moment, we have a need to connect to some third party web service and pull their data which is a huge xml file. Then process it. We need to do this at least once every 45 minutes. The owner will host this app some where and he doesn't want to pay for any components or extras. In this case, the only reliable way I found was to use some online services that can request your page or service on a schedule. I tested three of them that I found most interesting: http://www.cronservice.co.uk/new/, http://www.webbasedcron.com/ and http://scheduler.codeeffects.com/ Others that I found (there are TONS of them out there) seemed not reliable or poorly designed. I finally selected one of them and made the app owner to agree to use it on prod. So, don't go into that "oh well, we want our own code and no third parties" thing. Coding your own scheduler engine is difficult and takes a lot of time. I was testing one of those services for quite some time now and it works just fine for me. Just wanted to point this out :)

Tuesday, February 2, 2010 7:47 PM - Jaycent

The scenario I described earlier had the .exe running on my laptop at home. It connects to the remote web service at 30 second inetervals to download, parse, and store the rss feed into my sql server database on godaddy. So to be clear, the web service and database are located on godaddy servers, the exe that connect to the service can be on any computer anywhere (as long as there is an available connection to the internet).

Wednesday, February 3, 2010 11:38 AM - Tatworth

I suggest putting a sample web application project containing this code up on CodePlex.

Thursday, February 4, 2010 6:45 AM - Makki

I agree that this option is the best low cost method to trigger scheduled events. However, this isn't an option to critical operations like send news letters. Because this method cant grantee that it will trigger on time especially if the site is not popular

Thursday, February 4, 2010 5:23 PM - Steve Wellens

>>I'm also going to assume that the web application gets
>>enough visitors that Session_Start() will be fired often
>>enough to serve the purpose of trigger point.

If the above assumption is not true, you can look at these articles:

http://www.codeproject.com/KB/aspnet/ASPNETService.aspx
http://www.west-wind.com/WebLog/posts/67557.aspx

Thursday, February 4, 2010 8:15 PM - Adam W.

I use something similiar to this with ViewState. Have an Object in the Business project that determines where to save the viewstate (Database, FileSystem, Cache, or by default the page.)

Using session on start, a CleanUp() method is fired checking for Files or DB records (based on implementation) to remove. Using a variable to a timespan for leaving files or records the CleanUp will fire off and remove useless data.

At least in this scenario, WhenTaskLastRan is not needed. Session_OnStart will just fire the code. Obviously Storing files on the Server for ViewState in a hosted enviroment would be difficult on high volume sites with limited space, but it is possible. One thing overlooked by .Net applications that are hosted is the memory limititations that the hosting service will apply your ApplicationPool. Make sure that you don't exceed your memory limitations, because your Application Pool will recycle causing loss of sessions and such. Similiar to the Post by Vasha for Idle times.

You may want to investigate using a httpmodule instead. Add the Module to the Web.Config and use something like this.

Example
public class CleanUpHttpModule : IHttpModule
{
private const int CleanUpThreadSleep = 10000;
private static bool isRunningCleanUpThread = false;
const string cleanUpPath = YOUR_PATH;

private void CleanUp()
{
while (true)
{
// RunCleanUpCode
Thread.Sleep(CleanUpThreadSleep);
}
}

public void Init(HttpApplication context)
{
if (!isRunningCleanUpThread)
{
Thread thread = new Thread(new ThreadStart(CleanUp));
isRunningCleanUpThread = true;
thread.Start();
}
}
}

Friday, February 5, 2010 2:36 AM - JD

To Vasha which service did you go with?

Friday, February 5, 2010 12:14 PM - Adam W.

The example provided in my last post can be further explained and has code for examples at this url:

http://aspalliance.com/472_Persisting_View_State_to_the_File_System.all

Sunday, February 7, 2010 6:33 PM - Mike

It's interesting to observe the number of solutions provided in the comments that don't address the scenario described in the article....

:O)

Tuesday, February 9, 2010 4:33 AM - viet flex

Thanks, i think you can use Timer to run scheduling tasks.

Monday, February 15, 2010 12:34 AM - Vasha

To JD. Sorry, I missed your post. I currently use scheduler.codeeffects.com. No complains so far.

Wednesday, February 17, 2010 1:05 PM - Steve Walker

Compiler Error Message: CS1031: Type expected

Source Error:

Line 6: public static class ExtensionHelpers
Line 7: {
Line 8: public static bool IsOlderThan(this DateTime dt1, DateTime dt2)
Line 9: {
Line 10: return dt1 < dt2 ? true : false;

I always get this error when running the application? Any ideas? I found a post on asp.net that was slightly different to this one - however neither worked as expected and always complained about the IsOlderThan extension.

Regards,

Steve

Thursday, February 18, 2010 5:51 AM - Mike

@Steve

I suspect that you have not put the method in a class, or you have missed a brace.

Thursday, February 18, 2010 10:40 PM - Me

Nice article
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Bino 11/27/2014 7:05 PM
In response to MVC 5 with EF 6 in Visual Basic - Async and Stored Procedures with the Entity Framework
Copy +...

Manas 11/27/2014 5:30 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi Mike, Thank you for awesome article. My concern is it might impact website if we use or is...

priya 11/26/2014 6:50 PM
In response to Create PDFs in ASP.NET - getting started with iTextSharp
very nice.....its save my time...

ransems 11/24/2014 12:29 AM
In response to Adding A Controller
Love the article. I dislike that the world thinks c# articles are the way to go. Love the VB, keep...

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...