I would like to have a timer for an ASP.net application that will kick off every Sunday night and perform something (update a table in the database). However, I really don't want to write up a service that has to be deployed on the server in addition to the web application. Is there a way to accomplish this easily? Perhaps using a Global.asax file?
I'm not 100% sure where you would put it, but using a System.Threading.Timer would rock this.
// In some constructor or method that runs when the app starts.
// 1st parameter is the callback to be run every iteration.
// 2nd parameter is optional parameters for the callback.
// 3rd parameter is telling the timer when to start.
// 4th parameter is telling the timer how often to run.
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerElapsed), null, new Timespan(0), new Timespan(24, 0, 0));
// The callback, no inside the method used above.
// This will run every 24 hours.
private void TimerElapsed(object o)
{
// Do stuff.
}
Initially, you'll have to determine when to start the timer the first time, or you can turn the site on at the time you want this timer running on Sunday night.
But as others said, use something other than the site to do this. It's way easy to make a Windows service to deal with this.
I don't think a .NET application is a good solution to your problem.
IIS Recycling will recycle the process every few hours (depending on the setting) and even if you set that interval to seven days, the application pool can still be recycled for other reasons beyond your control.
I agree with jcrs3: Just write a little console app and use scheduler. You can also write a service, but if you need something quick and easy, go with the console app.
In response to your comment about Scheduled Tasks:
Another hack would be to override an event in Global.asax, an even that is called often like Application_EndRequest() and do something similar to:
protected void Application_EndRequest()
{
if (((DateTime)Application["lastTimeRun"]) < DateTime.Today)
{
Application["lastTimeRun"] = DateTime.Today;
doSomething();
}
}
This would run after the first request after the date changed, so you wouldn't be guaranteed that this would be run precisely at 3:00 AM every morning.
I've even seed cases where you would hit the site using a Scheduled Task on another computer.
It seems that the best solution was to use this technique. If I had more control over the server I would probably write up a console app to take advantage of scheduled tasks.