如何在共享托管服务器上按照配置的计划时间执行各种任务(例如电子邮件警报/发送新闻信)?
问问题
1953 次
3 回答
10
这是一个 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 分钟触发一次您的操作,但这可以在代码中进行配置。
于 2009-04-09T10:34:03.903 回答
0
有些人在这里通过在 global.asax 中创建线程来做到这一点。听起来他们在这方面取得了成功。我自己从未测试过这种方法。
在我看来,这将是一个更好的选择,然后重载缓存过期机制。
于 2009-04-09T11:07:07.193 回答
0
You can use ATrigger scheduling service on a shared hosting without any problem. A .Net library is also available to create scheduled tasks without overhead.
Disclaimer: I was among the ATrigger team. It's a freeware and I have not any commercial purpose.
于 2013-08-26T11:54:10.897 回答