如何在共享的托管服务器上按配置的计划时间执行各种任务(例如电子邮件警报/发送新闻信件)?
解决方法
这是一个Global.ascx.cs文件,我以前用过这种方式,使用缓存到期来触发计划任务:
public class Global : HttpApplication { private const string CACHE_ENTRY_KEY = "ServiceMimicCacheEntry"; private const string CACHE_KEY = "ServiceMimicCache"; private void Application_Start(object sender,EventArgs e) { Application[CACHE_KEY] = HttpContext.Current.Cache; RegisterCacheEntry(); } private void RegisterCacheEntry() { Cache cache = (Cache)Application[CACHE_KEY]; if (cache[CACHE_ENTRY_KEY] != null) return; cache.Add(CACHE_ENTRY_KEY,CACHE_ENTRY_KEY,null,DateTime.MaxValue,TimeSpan.FromSeconds(120),CacheItemPriority.Normal,new CacheItemRemovedCallback(CacheItemRemoved)); } private void SpawnServiceActions() { ThreadStart threadStart = new ThreadStart(DoServiceActions); Thread thread = new Thread(threadStart); thread.Start(); } private void DoServiceActions() { // do your scheduled stuff } private void CacheItemRemoved(string key,object value,CacheItemRemovedReason reason) { SpawnServiceActions(); RegisterCacheEntry(); } }
目前,这会每2分钟触发一次您的操作,但这可以在代码中配置.