在ASP.NET上启动维护过程的最佳实践是什么
对于ASP.NET应用程序,我需要定期(每天,每小时等)运行维护过程。
在不依赖于服务器上预定任务之类的外部流程的情况下,实现此目标的最佳方法是什么(假设我无权访问服务器共享的托管环境)。
解决方案
回答
如果我们不需要按计划的时间执行此操作,而只需要"偶尔一次"清理,那么一种方法是在Global.asax Session_OnEnd()中创建一个函数,该函数将创建一个随机变量。 1到100之间的数字,如果数字是50,则执行维护任务。
偏离路线时,可以减少" 100",以使任务更频繁地发生。
在http://www.codeproject.com/aspnet/ASPNETService.asp上也有标题为"使用ASP.NET模拟Windows服务以运行计划的作业"的文章,该文章使用过期缓存来模拟计时器。它声称它可以在任何托管站点上运行。
如果我们使用的是最后一种,请从有关此技术的帖子中阅读此评论:
You need to really be careful on the length of the task running. Every new Task is a new Worker Thread and there’s a limited number of those - as it “borrows” a thread from the managed thread pool. Starting in v3.5 of the Framework the maximum number of threads was increased 10x from 25 to 250. But there’s now a logarithmic startup to them, so as it doles out more threads it gets stingier with them. If you run out of available threads in the managed thread pool - your response times are going to go through the roof. What you’re really writing here is a messaging/queuing system. If you’re doing things like updating the cache, then by all means - kick off a new task. If you’re doing something like downloading a secondary HTTP resource or some kind of intensive database work - write a Windows Service and use a Queue that allows you more control over how much you “bite” off each time.
回答
这是StackOverflow的执行方式:
private static CacheItemRemovedCallback OnCacheRemove = null; protected void Application_Start(object sender, EventArgs e) { AddTask("DoStuff", 60); } private void AddTask(string name, int seconds) { OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved); HttpRuntime.Cache.Insert(name, seconds, null, DateTime.Now.AddSeconds(seconds), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove); } public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { // do stuff here if it matches our taskname, like WebRequest // re-add our task so it recurs AddTask(k, Convert.ToInt32(v)); }
详细信息:http://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
回答
这是一个外部过程,我不知道它的可靠性如何,但是我们可以在始终位于www.webcron.org的计算机上进行类似设置。
基本上,它的作用是按我们请求的时间表访问我们请求的页面。
从本质上讲,我们可以按计划在页面上执行任何操作,从而可以启动维护任务。
Jeff和Joel在最近的播客中还讨论了通过其他方法做类似的事情。
回答
尽管StackOverflow做到这一点的方式绝对是唯一的,但由于与之相关,因此我们可能还希望监视此问题。
回答
尽管Cache解决方案适用于简单情况,但如果日程安排需要更改,我们将很不走运。相反,我们可以使用Quartz.NET,它是流行的Java框架Quartz的端口,它非常灵活。