Triggering a timed event from the global.asax file
Posted: Tue Jun 23, 2009 10:33 am
There have been questions about how our maintenance code runs. This is handled with a .NET system timer. It's not something that is accessible. However you can approximate a timed event by a code modification to the global.asax file. Below is some functional sample code.
If you have your application running inside a web garden, be aware that the timer event will run once for each process. Explaining how to limit this to a single app instance is beyond the scope of my forum post.
This sample runs every ten seconds. The Logger statements are not necessary. I put them in so you can monitor the app_data/app.log file to confirm that your task is running. One thing to take note of is that this timer runs on a non ASPNET thread. There will be no HttpContext because there is no associated web request.
If you have your application running inside a web garden, be aware that the timer event will run once for each process. Explaining how to limit this to a single app instance is beyond the scope of my forum post.
This sample runs every ten seconds. The Logger statements are not necessary. I put them in so you can monitor the app_data/app.log file to confirm that your task is running. One thing to take note of is that this timer runs on a non ASPNET thread. There will be no HttpContext because there is no associated web request.
Code: Select all
// THIS VARIABLE HOLDS THE TIMER
private System.Threading.Timer timer;
protected void Application_Start(object sender, EventArgs e)
{
Logger.Info("Application Starting");
// SPECIFY THE NUMBER OF MILLISECONDS THAT THE TIMER WILL REPEAT
int intervalMilliseconds = 10000;
// THIS SETS UP THE TIMER
timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimedEvent), null, intervalMilliseconds, intervalMilliseconds);
}
protected void Application_End(object sender, EventArgs e)
{
Logger.Info("Application Ending");
if (timer != null) timer.Dispose();
}
private void TimedEvent(object stateInfo)
{
// THIS IS RUNNING ON ITS OWN THREAD, OUTSIDE OF HTTPCONTEXT
// (HTTPCONTEXT.CONTEXT IS NULL)
// YOU MUST INITIALIZE THE TOKEN FOR THE STORE, CHANGE THE ID IF IT IS OTHER THAN 1
Store store = StoreDataSource.Load(1);
// INITIALIZE THE TOKEN FOR THIS STORE
Token.Instance.InitStoreContext(store);
// *********
// PUT YOUR CODE BELOW THIS COMMENT
// *********
Logger.Info("Timed task is running...");
// *********
// PUT YOUR CODE ABOVE THIS COMMENT
// *********
// RESET THE TOKEN INSTANCE AFTER THE EVENT RUNS
Token.ResetInstance();
}