ASP.NET网站中的预定作业,无需购买专用服务器

时间:2009-04-09 10:29:09

标签: asp.net scheduling scheduled-tasks

如何在共享托管服务器上按已配置的计划时间执行各种任务(例如电子邮件提醒/发送新闻信件)?

3 个答案:

答案 0 :(得分: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分钟触发您的操作,但这可以在代码中配置。

答案 1 :(得分:0)

这里的Somone是通过在global.asax中创建线程来实现的。听起来他们正在取得成功。我自己从未测试过这种方法。

在我看来,这是一个更好的选择,然后重载缓存到期机制。

答案 2 :(得分:0)

您可以在共享主机上使用ATrigger计划服务,而不会出现任何问题.Net library也可用于创建计划任务而无需开销。

免责声明:我是ATrigger团队的一员。这是一个免费软件,我没有任何商业目的。

相关问题