Simple task Scheduling using Global asax

4.12 (43 votes)

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 ( or you might even consider using Sql Server Agent to run Jobs on a schedule ( 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)

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)
        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.


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: 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:
Last Updated:
Posted by:
Total Views to date: 85258


- 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.

- 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.

- 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.

- Pete

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

- Vasha

Guys. You are forgetting that run time will kill any threads (including the main 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:, and 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 :)

- 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).

- Tatworth

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

- 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

- 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:

- 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.

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

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

- JD

To Vasha which service did you go with?

- Adam W.

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

- Mike

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


- viet flex

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

- Vasha

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

- 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 that was slightly different to this one - however neither worked as expected and always complained about the IsOlderThan extension.



- Mike


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

- Me

Nice article

- Manoj Kalla

Very Good , Excellent.

Recent Comments

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....